TLS 加密缓冲问题

This commit is contained in:
2025-11-24 16:08:39 +08:00
parent 3f8fff331f
commit 7296b7881e

View File

@@ -10,10 +10,13 @@ const xmlparser = require('express-xml-bodyparser'); // 引入XML解析中间件
const https = require("https");
// 强制 IPv4 的 https agent
const ipv4Agent = new https.Agent({
family: 4, // 👈 最关键:强制 IPv4
keepAlive: true
family: 4, // 最关键:强制 IPv4
keepAlive: true,
maxSockets: 100,
keepAliveMsecs: 10000,
});
// 包一个强制 IPv4 的 fetch
@@ -24,6 +27,7 @@ const fetchIPv4 = (url, options = {}) => {
});
};
const bodyParser = require("body-parser");
const axios = require('axios');
const crypto = require('crypto');
@@ -117,22 +121,30 @@ app.use(express.urlencoded({ extended: true })); // 支持 form-data 字段
// 初始化客户端
const client = new OpenAI({
apiKey: "DxvRiQWROzLTapiSHcK0FXKAAXDBlhci1XaqTTpr50sgUsAkmxfUJQQJ99BIACYeBjFXJ3w3AAABACOGZdHp",
baseURL: "https://satabot.openai.azure.com/openai/deployments/gpt-4.1",
defaultQuery: { "api-version": "2024-04-01-preview" },
timeout: 120000,
fetch: fetchIPv4 // 👈 关键点:把自定义 fetch 注入 SDK
apiKey: "DxvRiQWROzLTapiSHcK0FXKAAXDBlhci1XaqTTpr50sgUsAkmxfUJQQJ99BIACYeBjFXJ3w3AAABACOGZdHp",
baseURL: "https://satabot.openai.azure.com/openai/deployments/gpt-4.1",
defaultQuery: { "api-version": "2024-04-01-preview" },
timeout: 120000,
fetch: fetchIPv4, // 关键点:把自定义 fetch 注入 SDK
// 确保底层也传 agent(可选,但保险)
baseOptions: {
agent: ipv4Agent
}
});
const client1 = new OpenAI({
apiKey: "DxvRiQWROzLTapiSHcK0FXKAAXDBlhci1XaqTTpr50sgUsAkmxfUJQQJ99BIACYeBjFXJ3w3AAABACOGZdHp",
baseURL: "https://satabot.openai.azure.com/openai/deployments/gpt-5-mini/",
defaultQuery: { "api-version": "2024-04-01-preview" },
timeout: 120000,
fetch: fetchIPv4 // 👈 关键点:把自定义 fetch 注入 SDK
apiKey: "DxvRiQWROzLTapiSHcK0FXKAAXDBlhci1XaqTTpr50sgUsAkmxfUJQQJ99BIACYeBjFXJ3w3AAABACOGZdHp",
baseURL: "https://satabot.openai.azure.com/openai/deployments/gpt-5-mini/",
defaultQuery: { "api-version": "2024-04-01-preview" },
timeout: 120000,
fetch: fetchIPv4, // 关键点:把自定义 fetch 注入 SDK
// 确保底层也传 agent(可选,但保险)
baseOptions: {
agent: ipv4Agent
}
});
async function test()
async function test1()
{
console.time("test");
await client.chat.completions.create({
@@ -143,8 +155,15 @@ async function test()
});
console.timeEnd("test");
}
async function directCall()
{
console.time("directCall");
await client1.chat.completions.create({ model:"gpt-5-mini", messages:[{ role: "user", content: "ping" }] });
console.timeEnd("directCall");
}
test();
test1();
directCall();
// 获取 access_token
// getAccessToken();
@@ -842,8 +861,8 @@ const stopFlags = new Map();
// ====================== API ======================
app.post("/analyze", upload.single("file"), async (req, res) => {
try
{
const { requestId } = req.body;
{
const { requestId } = req.body;
res.setHeader("Content-Type", "text/plain; charset=utf-8");
res.setHeader("Transfer-Encoding", "chunked");
@@ -856,6 +875,7 @@ app.post("/analyze", upload.single("file"), async (req, res) => {
});
console.time("analyze");
const logBody = { ...req.body };
if(req.body?.imageBase64)
{
@@ -955,26 +975,41 @@ app.post("/analyze", upload.single("file"), async (req, res) => {
console.log("====== 开始图像分析... ======")
let sceneText = "";
/* TLS 加密缓冲,小块数据可能先缓存在服务器端,不立即发送,会导致图像分析模型的结果不能立即返回 */
res.writeHead(200, {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
"Connection": "keep-alive",
});
res.socket.setNoDelay(true);
for await (const chunk of completion)
{
if (stopFlags.get(requestId)) {
console.log("⛔ 图像分析被前端中断");
res.end();
stopFlags.delete(requestId); // 用完清理
return;
}
if (stopFlags.get(requestId)) {
console.log("⛔ 图像分析被前端中断");
res.end();
stopFlags.delete(requestId); // 用完清理
return;
}
const delta = chunk.choices[0]?.delta?.content || "";
sceneText += delta;
if (delta)
{
res.write(
`data: ${JSON.stringify({ type: "scene", content: delta })}\n\n`
);
}
// if (delta)
// res.write(
// `data: ${JSON.stringify({ type: "scene", content: delta })}\n\n`
// );
if (delta) {
for (const ch of delta) {
res.write(`data: ${JSON.stringify({ type: "scene", content: ch })}\n\n`);
await new Promise(r => setTimeout(r, 0)); // 控制渲染节奏
}
}
// {
// for (const ch of delta)
// {
// res.write(`data: ${JSON.stringify({ type: "scene", content: ch })}\n\n`);
// await new Promise(r => setTimeout(r, 0)); // 控制渲染节奏
// }
// }
}
console.log("====== 图像分析结束 ======")
@@ -1027,19 +1062,21 @@ app.post("/analyze", upload.single("file"), async (req, res) => {
const delta = chunk.choices[0]?.delta?.content || "";
llmText += delta;
// if (delta)
// res.write(
// `data: ${JSON.stringify({ type: "llm", content: delta})}\n\n`
// );
if (delta)
{
for (const ch of delta)
{
res.write(`data: ${JSON.stringify({ type: "llm", content: ch })}\n\n`);
await new Promise(r => setTimeout(r, 0)); // 控制渲染节奏
}
}
res.write(
`data: ${JSON.stringify({ type: "llm", content: delta})}\n\n`
);
/* delta 很长,这会 人为拉长处理时间。 */
// if (delta)
// {
// for (const ch of delta)
// {
// res.write(`data: ${JSON.stringify({ type: "llm", content: ch })}\n\n`);
// await new Promise(r => setTimeout(r, 0)); // 控制渲染节奏
// }
// }
}
@@ -1090,7 +1127,8 @@ app.post("/analyze", upload.single("file"), async (req, res) => {
{
fs.unlinkSync(req.file.path);
}
console.log("====== 分析完成 ======")
console.log("====== 分析完成 ======");
console.timeEnd("analyze");
}
catch (err)
{