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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
const express = require("express");
|
| 2 |
+
const WebSocket = require("ws");
|
| 3 |
+
const http = require("http");
|
| 4 |
+
const { EventEmitter } = require("events");
|
| 5 |
+
const MY_SECRET_KEY = process.env.MY_SECRET_KEY || "123456";
|
| 6 |
+
|
| 7 |
+
// --- LoggingService (无变动) ---
|
| 8 |
+
class LoggingService {
|
| 9 |
+
constructor(serviceName = "ProxyServer") {
|
| 10 |
+
this.serviceName = serviceName;
|
| 11 |
+
}
|
| 12 |
+
_formatMessage(level, message) {
|
| 13 |
+
const timestamp = new Date().toISOString();
|
| 14 |
+
return `[${level}] ${timestamp} [${this.serviceName}] - ${message}`;
|
| 15 |
+
}
|
| 16 |
+
info(message) {
|
| 17 |
+
console.log(this._formatMessage("INFO", message));
|
| 18 |
+
}
|
| 19 |
+
error(message) {
|
| 20 |
+
console.error(this._formatMessage("ERROR", message));
|
| 21 |
+
}
|
| 22 |
+
warn(message) {
|
| 23 |
+
console.warn(this._formatMessage("WARN", message));
|
| 24 |
+
}
|
| 25 |
+
debug(message) {
|
| 26 |
+
console.debug(this._formatMessage("DEBUG", message));
|
| 27 |
+
}
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
// --- MessageQueue (无变动) ---
|
| 31 |
+
class MessageQueue extends EventEmitter {
|
| 32 |
+
constructor(timeoutMs = 600000) {
|
| 33 |
+
super();
|
| 34 |
+
this.messages = [];
|
| 35 |
+
this.waitingResolvers = [];
|
| 36 |
+
this.defaultTimeout = timeoutMs;
|
| 37 |
+
this.closed = false;
|
| 38 |
+
}
|
| 39 |
+
enqueue(message) {
|
| 40 |
+
if (this.closed) return;
|
| 41 |
+
if (this.waitingResolvers.length > 0) {
|
| 42 |
+
this.waitingResolvers.shift().resolve(message);
|
| 43 |
+
} else {
|
| 44 |
+
this.messages.push(message);
|
| 45 |
+
}
|
| 46 |
+
}
|
| 47 |
+
async dequeue(timeoutMs = this.defaultTimeout) {
|
| 48 |
+
if (this.closed) throw new Error("Queue is closed");
|
| 49 |
+
return new Promise((resolve, reject) => {
|
| 50 |
+
if (this.messages.length > 0) {
|
| 51 |
+
resolve(this.messages.shift());
|
| 52 |
+
return;
|
| 53 |
+
}
|
| 54 |
+
const resolver = { resolve, reject };
|
| 55 |
+
this.waitingResolvers.push(resolver);
|
| 56 |
+
const timeoutId = setTimeout(() => {
|
| 57 |
+
const index = this.waitingResolvers.indexOf(resolver);
|
| 58 |
+
if (index !== -1) {
|
| 59 |
+
this.waitingResolvers.splice(index, 1);
|
| 60 |
+
reject(new Error("Queue timeout"));
|
| 61 |
+
}
|
| 62 |
+
}, timeoutMs);
|
| 63 |
+
resolver.timeoutId = timeoutId;
|
| 64 |
+
});
|
| 65 |
+
}
|
| 66 |
+
close() {
|
| 67 |
+
this.closed = true;
|
| 68 |
+
this.waitingResolvers.forEach((r) => {
|
| 69 |
+
clearTimeout(r.timeoutId);
|
| 70 |
+
r.reject(new Error("Queue closed"));
|
| 71 |
+
});
|
| 72 |
+
this.waitingResolvers = [];
|
| 73 |
+
this.messages = [];
|
| 74 |
+
}
|
| 75 |
+
}
|
| 76 |
+
|
| 77 |
+
// --- ConnectionRegistry (无变动) ---
|
| 78 |
+
class ConnectionRegistry extends EventEmitter {
|
| 79 |
+
constructor(logger) {
|
| 80 |
+
super();
|
| 81 |
+
this.logger = logger;
|
| 82 |
+
this.connections = new Set();
|
| 83 |
+
this.messageQueues = new Map();
|
| 84 |
+
this.heartbeatInterval = null; // 用于存放计时器ID
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
// 新增:心跳检测函数
|
| 88 |
+
_startHeartbeat() {
|
| 89 |
+
this.logger.info("心跳检测机制已启动。");
|
| 90 |
+
// 清除旧的计时器以防万一
|
| 91 |
+
if (this.heartbeatInterval) clearInterval(this.heartbeatInterval);
|
| 92 |
+
|
| 93 |
+
this.heartbeatInterval = setInterval(() => {
|
| 94 |
+
this.connections.forEach((ws) => {
|
| 95 |
+
if (ws.isAlive === false) {
|
| 96 |
+
this.logger.warn(`检测到僵尸连接,正在终止...`);
|
| 97 |
+
return ws.terminate(); // 强制终止不响应的连接
|
| 98 |
+
}
|
| 99 |
+
ws.isAlive = false; // 假设它死了,等待pong来证明它活着
|
| 100 |
+
ws.ping(() => {}); // 发送ping
|
| 101 |
+
});
|
| 102 |
+
}, 30000); // 每30秒检测一次
|
| 103 |
+
}
|
| 104 |
+
|
| 105 |
+
// 新增:停止心跳检测
|
| 106 |
+
_stopHeartbeat() {
|
| 107 |
+
if (this.heartbeatInterval) {
|
| 108 |
+
clearInterval(this.heartbeatInterval);
|
| 109 |
+
this.heartbeatInterval = null;
|
| 110 |
+
this.logger.info("连接全部断开,心跳检测机制已停止。");
|
| 111 |
+
}
|
| 112 |
+
}
|
| 113 |
+
|
| 114 |
+
addConnection(websocket, clientInfo) {
|
| 115 |
+
websocket.isAlive = true; // 初始化时,我们认为它是活的
|
| 116 |
+
this.connections.add(websocket);
|
| 117 |
+
this.logger.info(`新客户端连接: ${clientInfo.address}`);
|
| 118 |
+
|
| 119 |
+
// 当收到pong时,标记为存活
|
| 120 |
+
websocket.on("pong", () => {
|
| 121 |
+
websocket.isAlive = true;
|
| 122 |
+
});
|
| 123 |
+
|
| 124 |
+
websocket.on("message", (data) =>
|
| 125 |
+
this._handleIncomingMessage(data.toString())
|
| 126 |
+
);
|
| 127 |
+
websocket.on("close", () => this._removeConnection(websocket));
|
| 128 |
+
websocket.on("error", (error) =>
|
| 129 |
+
this.logger.error(`WebSocket连接错误: ${error.message}`)
|
| 130 |
+
);
|
| 131 |
+
|
| 132 |
+
if (this.connections.size === 1) {
|
| 133 |
+
this._startHeartbeat(); // 当第一个连接建立时,启动心跳
|
| 134 |
+
}
|
| 135 |
+
this.emit("connectionAdded", websocket);
|
| 136 |
+
}
|
| 137 |
+
|
| 138 |
+
_removeConnection(websocket) {
|
| 139 |
+
this.connections.delete(websocket);
|
| 140 |
+
this.logger.info("客户端连接断开");
|
| 141 |
+
this.messageQueues.forEach((queue) => queue.close());
|
| 142 |
+
this.messageQueues.clear();
|
| 143 |
+
|
| 144 |
+
if (this.connections.size === 0) {
|
| 145 |
+
this._stopHeartbeat(); // 当所有连接都断开时,停止心跳
|
| 146 |
+
}
|
| 147 |
+
this.emit("connectionRemoved", websocket);
|
| 148 |
+
}
|
| 149 |
+
|
| 150 |
+
// _handleIncomingMessage, hasActiveConnections, getFirstConnection,
|
| 151 |
+
// createMessageQueue, removeMessageQueue 这些方法保持不变
|
| 152 |
+
_handleIncomingMessage(messageData) {
|
| 153 |
+
try {
|
| 154 |
+
const parsedMessage = JSON.parse(messageData);
|
| 155 |
+
const { request_id, event_type } = parsedMessage;
|
| 156 |
+
if (!request_id) {
|
| 157 |
+
this.logger.warn("收到无效消息:缺少request_id");
|
| 158 |
+
return;
|
| 159 |
+
}
|
| 160 |
+
const queue = this.messageQueues.get(request_id);
|
| 161 |
+
if (queue) {
|
| 162 |
+
switch (event_type) {
|
| 163 |
+
case "response_headers":
|
| 164 |
+
case "chunk":
|
| 165 |
+
case "error":
|
| 166 |
+
queue.enqueue(parsedMessage);
|
| 167 |
+
break;
|
| 168 |
+
case "stream_close":
|
| 169 |
+
queue.enqueue({ type: "STREAM_END" });
|
| 170 |
+
break;
|
| 171 |
+
default:
|
| 172 |
+
this.logger.warn(`未知的事件类型: ${event_type}`);
|
| 173 |
+
}
|
| 174 |
+
} else {
|
| 175 |
+
this.logger.warn(`收到未知请求ID的消息: ${request_id}`);
|
| 176 |
+
}
|
| 177 |
+
} catch (error) {
|
| 178 |
+
this.logger.error("解析WebSocket消息失败");
|
| 179 |
+
}
|
| 180 |
+
}
|
| 181 |
+
|
| 182 |
+
hasActiveConnections() {
|
| 183 |
+
return this.connections.size > 0;
|
| 184 |
+
}
|
| 185 |
+
|
| 186 |
+
getFirstConnection() {
|
| 187 |
+
// 筛选出真正存活的连接
|
| 188 |
+
const aliveConnections = Array.from(this.connections).filter(
|
| 189 |
+
(ws) => ws.isAlive
|
| 190 |
+
);
|
| 191 |
+
if (aliveConnections.length === 0 && this.connections.size > 0) {
|
| 192 |
+
this.logger.warn("有连接记录,但没有一个通过心跳检测!");
|
| 193 |
+
}
|
| 194 |
+
return aliveConnections[0]; // 总是返回第一个健康的连接
|
| 195 |
+
}
|
| 196 |
+
|
| 197 |
+
createMessageQueue(requestId) {
|
| 198 |
+
const queue = new MessageQueue();
|
| 199 |
+
this.messageQueues.set(requestId, queue);
|
| 200 |
+
return queue;
|
| 201 |
+
}
|
| 202 |
+
|
| 203 |
+
removeMessageQueue(requestId) {
|
| 204 |
+
const queue = this.messageQueues.get(requestId);
|
| 205 |
+
if (queue) {
|
| 206 |
+
queue.close();
|
| 207 |
+
this.messageQueues.delete(requestId);
|
| 208 |
+
}
|
| 209 |
+
}
|
| 210 |
+
}
|
| 211 |
+
|
| 212 |
+
// --- RequestHandler (无变动) ---
|
| 213 |
+
class RequestHandler {
|
| 214 |
+
constructor(serverSystem, connectionRegistry, logger) {
|
| 215 |
+
this.serverSystem = serverSystem;
|
| 216 |
+
this.connectionRegistry = connectionRegistry;
|
| 217 |
+
this.logger = logger;
|
| 218 |
+
this.maxRetries = 3;
|
| 219 |
+
this.retryDelay = 2000;
|
| 220 |
+
}
|
| 221 |
+
|
| 222 |
+
async processRequest(req, res) {
|
| 223 |
+
// 不再检查请求头,而是检查URL查询参数中的'key'字段。
|
| 224 |
+
const clientKey = req.query.key;
|
| 225 |
+
|
| 226 |
+
if (!clientKey || clientKey !== MY_SECRET_KEY) {
|
| 227 |
+
this.logger.warn(
|
| 228 |
+
`收到一个无效的或缺失的代理密码,已拒绝。请求路径: ${req.url}`
|
| 229 |
+
);
|
| 230 |
+
return this._sendErrorResponse(
|
| 231 |
+
res,
|
| 232 |
+
401,
|
| 233 |
+
"Unauthorized - Invalid API Key in URL parameter"
|
| 234 |
+
);
|
| 235 |
+
}
|
| 236 |
+
|
| 237 |
+
// 验证通过,移除URL中的key参数,避免它被发送到Google
|
| 238 |
+
delete req.query.key;
|
| 239 |
+
|
| 240 |
+
this.logger.info(`代理密码验证通过。处理请求: ${req.method} ${req.path}`);
|
| 241 |
+
|
| 242 |
+
if (!this.connectionRegistry.hasActiveConnections()) {
|
| 243 |
+
return this._sendErrorResponse(res, 503, "没有可用的浏览器连接");
|
| 244 |
+
}
|
| 245 |
+
|
| 246 |
+
const requestId = this._generateRequestId();
|
| 247 |
+
const proxyRequest = this._buildProxyRequest(req, requestId);
|
| 248 |
+
const messageQueue = this.connectionRegistry.createMessageQueue(requestId);
|
| 249 |
+
|
| 250 |
+
try {
|
| 251 |
+
if (this.serverSystem.streamingMode === "fake") {
|
| 252 |
+
await this._handlePseudoStreamResponse(
|
| 253 |
+
proxyRequest,
|
| 254 |
+
messageQueue,
|
| 255 |
+
req,
|
| 256 |
+
res
|
| 257 |
+
);
|
| 258 |
+
} else {
|
| 259 |
+
await this._handleRealStreamResponse(proxyRequest, messageQueue, res);
|
| 260 |
+
}
|
| 261 |
+
} catch (error) {
|
| 262 |
+
this._handleRequestError(error, res);
|
| 263 |
+
} finally {
|
| 264 |
+
this.connectionRegistry.removeMessageQueue(requestId);
|
| 265 |
+
}
|
| 266 |
+
}
|
| 267 |
+
_generateRequestId() {
|
| 268 |
+
return `${Date.now()}_${Math.random().toString(36).substring(2, 11)}`;
|
| 269 |
+
}
|
| 270 |
+
_buildProxyRequest(req, requestId) {
|
| 271 |
+
let requestBody = "";
|
| 272 |
+
if (Buffer.isBuffer(req.body)) {
|
| 273 |
+
requestBody = req.body.toString("utf-8");
|
| 274 |
+
} else if (typeof req.body === "string") {
|
| 275 |
+
requestBody = req.body;
|
| 276 |
+
} else if (req.body) {
|
| 277 |
+
requestBody = JSON.stringify(req.body);
|
| 278 |
+
}
|
| 279 |
+
return {
|
| 280 |
+
path: req.path,
|
| 281 |
+
method: req.method,
|
| 282 |
+
headers: req.headers,
|
| 283 |
+
query_params: req.query,
|
| 284 |
+
body: requestBody,
|
| 285 |
+
request_id: requestId,
|
| 286 |
+
streaming_mode: this.serverSystem.streamingMode,
|
| 287 |
+
};
|
| 288 |
+
}
|
| 289 |
+
_forwardRequest(proxyRequest) {
|
| 290 |
+
const connection = this.connectionRegistry.getFirstConnection();
|
| 291 |
+
if (connection) {
|
| 292 |
+
connection.send(JSON.stringify(proxyRequest));
|
| 293 |
+
} else {
|
| 294 |
+
throw new Error("无法转发请求:没有可用的WebSocket连接。");
|
| 295 |
+
}
|
| 296 |
+
}
|
| 297 |
+
_sendErrorChunkToClient(res, errorMessage) {
|
| 298 |
+
const errorPayload = {
|
| 299 |
+
error: {
|
| 300 |
+
message: `[代理系统提示] ${errorMessage}`,
|
| 301 |
+
type: "proxy_error",
|
| 302 |
+
code: "proxy_error",
|
| 303 |
+
},
|
| 304 |
+
};
|
| 305 |
+
const chunk = `data: ${JSON.stringify(errorPayload)}\n\n`;
|
| 306 |
+
if (res && !res.writableEnded) {
|
| 307 |
+
res.write(chunk);
|
| 308 |
+
this.logger.info(`已向客户端发送标准错误信号: ${errorMessage}`);
|
| 309 |
+
}
|
| 310 |
+
}
|
| 311 |
+
|
| 312 |
+
async _handlePseudoStreamResponse(proxyRequest, messageQueue, req, res) {
|
| 313 |
+
res.status(200).set({
|
| 314 |
+
"Content-Type": "text/event-stream",
|
| 315 |
+
"Cache-Control": "no-cache",
|
| 316 |
+
Connection: "keep-alive",
|
| 317 |
+
});
|
| 318 |
+
this.logger.info("已向客户端发送初始响应头,假流式计时器已启动。");
|
| 319 |
+
let connectionMaintainer = null;
|
| 320 |
+
try {
|
| 321 |
+
const keepAliveChunk = this._getKeepAliveChunk(req);
|
| 322 |
+
connectionMaintainer = setInterval(() => {
|
| 323 |
+
if (!res.writableEnded) {
|
| 324 |
+
res.write(keepAliveChunk);
|
| 325 |
+
}
|
| 326 |
+
}, 1000);
|
| 327 |
+
|
| 328 |
+
// --- 移除了服务器端的 for 循环重试 ---
|
| 329 |
+
this.logger.info(`请求已派发给浏览器端处理...`);
|
| 330 |
+
this._forwardRequest(proxyRequest);
|
| 331 |
+
|
| 332 |
+
// 等待浏览器端的最终处理结果(成功或失败)
|
| 333 |
+
const lastMessage = await messageQueue.dequeue();
|
| 334 |
+
|
| 335 |
+
// 如果浏览器端报告了错误,直接抛出,不再重试
|
| 336 |
+
if (lastMessage.event_type === "error") {
|
| 337 |
+
const errorText = `浏览器端报告错误: ${lastMessage.status || ""} ${
|
| 338 |
+
lastMessage.message || "未知错误"
|
| 339 |
+
}`;
|
| 340 |
+
this._sendErrorChunkToClient(res, errorText);
|
| 341 |
+
throw new Error(errorText);
|
| 342 |
+
}
|
| 343 |
+
|
| 344 |
+
const dataMessage = await messageQueue.dequeue();
|
| 345 |
+
const endMessage = await messageQueue.dequeue();
|
| 346 |
+
|
| 347 |
+
if (dataMessage.data) {
|
| 348 |
+
res.write(`data: ${dataMessage.data}\n\n`);
|
| 349 |
+
this.logger.info("已将完整响应体作为SSE事件发送。");
|
| 350 |
+
}
|
| 351 |
+
if (endMessage.type !== "STREAM_END") {
|
| 352 |
+
this.logger.warn("未收到预期的流结束信号。");
|
| 353 |
+
}
|
| 354 |
+
} finally {
|
| 355 |
+
if (connectionMaintainer) clearInterval(connectionMaintainer);
|
| 356 |
+
if (!res.writableEnded) res.end();
|
| 357 |
+
this.logger.info("假流式响应处理结束。");
|
| 358 |
+
}
|
| 359 |
+
}
|
| 360 |
+
|
| 361 |
+
async _handleRealStreamResponse(proxyRequest, messageQueue, res) {
|
| 362 |
+
let headerMessage;
|
| 363 |
+
for (let attempt = 1; attempt <= this.maxRetries; attempt++) {
|
| 364 |
+
this.logger.info(`请求尝试 #${attempt}/${this.maxRetries}...`);
|
| 365 |
+
this._forwardRequest(proxyRequest);
|
| 366 |
+
headerMessage = await messageQueue.dequeue();
|
| 367 |
+
if (
|
| 368 |
+
headerMessage.event_type === "error" &&
|
| 369 |
+
headerMessage.status >= 400 &&
|
| 370 |
+
headerMessage.status <= 599
|
| 371 |
+
) {
|
| 372 |
+
this.logger.warn(
|
| 373 |
+
`收到 ${headerMessage.status} 错误,将在 ${
|
| 374 |
+
this.retryDelay / 1000
|
| 375 |
+
}秒后重试...`
|
| 376 |
+
);
|
| 377 |
+
if (attempt < this.maxRetries) {
|
| 378 |
+
await new Promise((resolve) => setTimeout(resolve, this.retryDelay));
|
| 379 |
+
continue;
|
| 380 |
+
}
|
| 381 |
+
}
|
| 382 |
+
break;
|
| 383 |
+
}
|
| 384 |
+
if (headerMessage.event_type === "error") {
|
| 385 |
+
return this._sendErrorResponse(
|
| 386 |
+
res,
|
| 387 |
+
headerMessage.status,
|
| 388 |
+
headerMessage.message
|
| 389 |
+
);
|
| 390 |
+
}
|
| 391 |
+
this._setResponseHeaders(res, headerMessage);
|
| 392 |
+
this.logger.info("已向客户端发送真实响应头,开始流式传输...");
|
| 393 |
+
try {
|
| 394 |
+
while (true) {
|
| 395 |
+
const dataMessage = await messageQueue.dequeue(30000);
|
| 396 |
+
if (dataMessage.type === "STREAM_END") {
|
| 397 |
+
this.logger.info("收到流结束信号。");
|
| 398 |
+
break;
|
| 399 |
+
}
|
| 400 |
+
if (dataMessage.data) res.write(dataMessage.data);
|
| 401 |
+
}
|
| 402 |
+
} catch (error) {
|
| 403 |
+
if (error.message !== "Queue timeout") throw error;
|
| 404 |
+
this.logger.warn("真流式响应超时,可能流已正常结束。");
|
| 405 |
+
} finally {
|
| 406 |
+
if (!res.writableEnded) res.end();
|
| 407 |
+
this.logger.info("真流式响应连接已关闭。");
|
| 408 |
+
}
|
| 409 |
+
}
|
| 410 |
+
_getKeepAliveChunk(req) {
|
| 411 |
+
if (req.path.includes("chat/completions")) {
|
| 412 |
+
const payload = {
|
| 413 |
+
id: `chatcmpl-${this._generateRequestId()}`,
|
| 414 |
+
object: "chat.completion.chunk",
|
| 415 |
+
created: Math.floor(Date.now() / 1000),
|
| 416 |
+
model: "gpt-4",
|
| 417 |
+
choices: [{ index: 0, delta: {}, finish_reason: null }],
|
| 418 |
+
};
|
| 419 |
+
return `data: ${JSON.stringify(payload)}\n\n`;
|
| 420 |
+
}
|
| 421 |
+
if (
|
| 422 |
+
req.path.includes("generateContent") ||
|
| 423 |
+
req.path.includes("streamGenerateContent")
|
| 424 |
+
) {
|
| 425 |
+
const payload = {
|
| 426 |
+
candidates: [
|
| 427 |
+
{
|
| 428 |
+
content: { parts: [{ text: "" }], role: "model" },
|
| 429 |
+
finishReason: null,
|
| 430 |
+
index: 0,
|
| 431 |
+
safetyRatings: [],
|
| 432 |
+
},
|
| 433 |
+
],
|
| 434 |
+
};
|
| 435 |
+
return `data: ${JSON.stringify(payload)}\n\n`;
|
| 436 |
+
}
|
| 437 |
+
return "data: {}\n\n";
|
| 438 |
+
}
|
| 439 |
+
_setResponseHeaders(res, headerMessage) {
|
| 440 |
+
res.status(headerMessage.status || 200);
|
| 441 |
+
const headers = headerMessage.headers || {};
|
| 442 |
+
Object.entries(headers).forEach(([name, value]) => {
|
| 443 |
+
if (name.toLowerCase() !== "content-length") res.set(name, value);
|
| 444 |
+
});
|
| 445 |
+
}
|
| 446 |
+
_handleRequestError(error, res) {
|
| 447 |
+
if (res.headersSent) {
|
| 448 |
+
this.logger.error(`请求处理错误 (头已发送): ${error.message}`);
|
| 449 |
+
if (this.serverSystem.streamingMode === "fake") {
|
| 450 |
+
this._sendErrorChunkToClient(res, `处理失败: ${error.message}`);
|
| 451 |
+
}
|
| 452 |
+
if (!res.writableEnded) res.end();
|
| 453 |
+
} else {
|
| 454 |
+
this.logger.error(`请求处理错误: ${error.message}`);
|
| 455 |
+
this._sendErrorResponse(
|
| 456 |
+
res,
|
| 457 |
+
error.message.includes("超时") ? 504 : 500,
|
| 458 |
+
`代理错误: ${error.message}`
|
| 459 |
+
);
|
| 460 |
+
}
|
| 461 |
+
}
|
| 462 |
+
_sendErrorResponse(res, status, message) {
|
| 463 |
+
if (!res.headersSent)
|
| 464 |
+
res
|
| 465 |
+
.status(status || 500)
|
| 466 |
+
.type("text/plain")
|
| 467 |
+
.send(message);
|
| 468 |
+
}
|
| 469 |
+
}
|
| 470 |
+
|
| 471 |
+
class ProxyServerSystem extends EventEmitter {
|
| 472 |
+
constructor(config = {}) {
|
| 473 |
+
super();
|
| 474 |
+
// 端口从环境变量读取,7860是Hugging Face常用的一个默认值
|
| 475 |
+
const PORT = process.env.PORT || 7860;
|
| 476 |
+
this.config = {
|
| 477 |
+
port: PORT, // 使用动态端口
|
| 478 |
+
host: "0.0.0.0",
|
| 479 |
+
// SSL证书不再需要
|
| 480 |
+
// sslKeyPath: "./key.pem",
|
| 481 |
+
// sslCertPath: "./cert.pem",
|
| 482 |
+
...config,
|
| 483 |
+
};
|
| 484 |
+
this.streamingMode = "fake";
|
| 485 |
+
this.logger = new LoggingService("ProxyServer");
|
| 486 |
+
this.connectionRegistry = new ConnectionRegistry(this.logger);
|
| 487 |
+
this.requestHandler = new RequestHandler(
|
| 488 |
+
this,
|
| 489 |
+
this.connectionRegistry,
|
| 490 |
+
this.logger
|
| 491 |
+
);
|
| 492 |
+
this.server = null;
|
| 493 |
+
this.wsServer = null;
|
| 494 |
+
}
|
| 495 |
+
|
| 496 |
+
async start() {
|
| 497 |
+
try {
|
| 498 |
+
await this._startServer();
|
| 499 |
+
this.logger.info(
|
| 500 |
+
`代理服务器系统启动完成,当前模式: ${this.streamingMode}`
|
| 501 |
+
);
|
| 502 |
+
this.emit("started");
|
| 503 |
+
} catch (error) {
|
| 504 |
+
this.logger.error(`启动失败: ${error.message}`);
|
| 505 |
+
this.emit("error", error);
|
| 506 |
+
throw error;
|
| 507 |
+
}
|
| 508 |
+
}
|
| 509 |
+
|
| 510 |
+
_createExpressApp() {
|
| 511 |
+
const app = express();
|
| 512 |
+
app.use(express.json({ limit: "100mb" }));
|
| 513 |
+
app.use(express.urlencoded({ extended: true, limit: "100mb" }));
|
| 514 |
+
app.use(express.raw({ type: "*/*", limit: "100mb" }));
|
| 515 |
+
|
| 516 |
+
app.get("/admin/set-mode", (req, res) => {
|
| 517 |
+
const newMode = req.query.mode;
|
| 518 |
+
if (newMode === "fake" || newMode === "real") {
|
| 519 |
+
this.streamingMode = newMode;
|
| 520 |
+
const message = `流式响应模式已切换为: ${this.streamingMode}`;
|
| 521 |
+
this.logger.info(message);
|
| 522 |
+
res.status(200).send(message);
|
| 523 |
+
} else {
|
| 524 |
+
const message = '无效的模式。请使用 "fake" 或 "real"。';
|
| 525 |
+
this.logger.warn(message);
|
| 526 |
+
res.status(400).send(message);
|
| 527 |
+
}
|
| 528 |
+
});
|
| 529 |
+
|
| 530 |
+
app.get("/admin/get-mode", (req, res) => {
|
| 531 |
+
res.status(200).send(`当前流式响应模式为: ${this.streamingMode}`);
|
| 532 |
+
});
|
| 533 |
+
|
| 534 |
+
app.all(/(.*)/, (req, res, next) => {
|
| 535 |
+
if (req.path === "/") {
|
| 536 |
+
this.logger.info(`根目录'/'被访问,发送状态页面。`);
|
| 537 |
+
if (this.connectionRegistry.hasActiveConnections()) {
|
| 538 |
+
return res
|
| 539 |
+
.status(200)
|
| 540 |
+
.send("✅ A browser client is connected. The proxy is ready.");
|
| 541 |
+
} else {
|
| 542 |
+
return res
|
| 543 |
+
.status(404)
|
| 544 |
+
.send(
|
| 545 |
+
"❌ No browser client connected. Please run the browser script."
|
| 546 |
+
);
|
| 547 |
+
}
|
| 548 |
+
}
|
| 549 |
+
|
| 550 |
+
if (req.path.startsWith("/admin/")) return next();
|
| 551 |
+
if (req.path === "/favicon.ico") return res.status(204).send();
|
| 552 |
+
this.requestHandler.processRequest(req, res);
|
| 553 |
+
});
|
| 554 |
+
|
| 555 |
+
return app;
|
| 556 |
+
}
|
| 557 |
+
|
| 558 |
+
async _startServer() {
|
| 559 |
+
const app = this._createExpressApp();
|
| 560 |
+
const httpServer = http.createServer(app);
|
| 561 |
+
this.server = httpServer;
|
| 562 |
+
this.wsServer = new WebSocket.Server({ server: httpServer });
|
| 563 |
+
|
| 564 |
+
this.wsServer.on("connection", (ws, req) => {
|
| 565 |
+
this.connectionRegistry.addConnection(ws, {
|
| 566 |
+
address: req.socket.remoteAddress,
|
| 567 |
+
});
|
| 568 |
+
});
|
| 569 |
+
|
| 570 |
+
return new Promise((resolve) => {
|
| 571 |
+
this.server.listen(this.config.port, this.config.host, () => {
|
| 572 |
+
this.logger.info(
|
| 573 |
+
`HTTP服务器启动: http://${this.config.host}:${this.config.port}`
|
| 574 |
+
);
|
| 575 |
+
this.logger.info(
|
| 576 |
+
`WS服务器正在监听: ws://${this.config.host}:${this.config.port}`
|
| 577 |
+
);
|
| 578 |
+
resolve();
|
| 579 |
+
});
|
| 580 |
+
});
|
| 581 |
+
}
|
| 582 |
+
}
|
| 583 |
+
|
| 584 |
+
// --- Main execution block (无变动) ---
|
| 585 |
+
async function initializeServer() {
|
| 586 |
+
const serverSystem = new ProxyServerSystem();
|
| 587 |
+
try {
|
| 588 |
+
await serverSystem.start();
|
| 589 |
+
} catch (error) {
|
| 590 |
+
console.error("服务器启动失败:", error.message);
|
| 591 |
+
process.exit(1);
|
| 592 |
+
}
|
| 593 |
+
}
|
| 594 |
+
if (require.main === module) {
|
| 595 |
+
initializeServer();
|
| 596 |
+
}
|
| 597 |
+
module.exports = { ProxyServerSystem, initializeServer };
|