fix: mongo内存泄漏

This commit is contained in:
Archer
2023-03-10 18:54:51 +08:00
parent 65da4653bc
commit 453f3be8ce
6 changed files with 69 additions and 55 deletions

View File

@@ -8,7 +8,7 @@
animation: blink 0.6s infinite;
}
.animation {
:last-child::after {
> :last-child::after {
display: inline-block;
content: '';
width: 4px;

View File

@@ -69,25 +69,21 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
stream: true
},
{
timeout: 20000,
responseType: 'stream',
httpsAgent: openaiProxy?.httpsAgent
}
);
console.log('response success');
let AIResponse = '';
// 解析数据
const decoder = new TextDecoder();
new ReadableStream({
async start(controller) {
// callback
async function onParse(event: ParsedEvent | ReconnectInterval) {
const onParse = async (event: ParsedEvent | ReconnectInterval) => {
if (event.type === 'event') {
const data = event.data;
if (data === '[DONE]') {
controller.close();
res.write('event: done\ndata: \n\n');
res.end();
// 存入库
await ChatWindow.findByIdAndUpdate(windowId, {
$push: {
@@ -98,27 +94,26 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
},
updateTime: Date.now()
});
res.write('event: done\ndata: \n\n');
res.end();
return;
}
try {
const json = JSON.parse(data);
const content: string = json.choices[0].delta.content || '';
// console.log('content:', content)
res.write(`event: responseData\ndata: ${content.replace(/\n/g, '<br/>')}\n\n`);
AIResponse += content;
} catch (e) {
// maybe parse error
controller.error(e);
res.end();
}
}
}
};
const parser = createParser(onParse);
for await (const chunk of chatResponse.data as any) {
parser.feed(decoder.decode(chunk));
}
}
});
} catch (err: any) {
let errorText = err;
if (err.code === 'ECONNRESET') {

View File

@@ -127,14 +127,14 @@ const Chat = () => {
let timer = setTimeout(() => {
event.close();
reject('服务器超时');
}, 300000);
}, 30000);
event.addEventListener('responseData', ({ data }) => {
/* 重置定时器 */
clearTimeout(timer);
timer = setTimeout(() => {
event.close();
reject('服务器超时');
}, 300000);
}, 30000);
const msg = data.replace(/<br\/>/g, '\n');
setChatList((state) =>
@@ -264,7 +264,7 @@ const Chat = () => {
const reEdit = useCallback(async () => {
if (chatList[chatList.length - 1]?.obj !== 'Human') return;
// 删除数据库最后一句
delLastMessage(windowId);
await delLastMessage(windowId);
const val = chatList[chatList.length - 1].value;
setInputVal(val);

View File

@@ -1,18 +1,28 @@
import mongoose from 'mongoose';
import type { Mongoose } from 'mongoose';
let cachedClient: Mongoose;
export async function connectToDatabase() {
if (cachedClient && cachedClient.connection.readyState === 1) {
return cachedClient;
/**
* 连接 MongoDB 数据库
*/
export async function connectToDatabase(): Promise<void> {
// @ts-ignore
if (global.mongodb) {
return;
}
cachedClient = await mongoose.connect(process.env.MONGODB_URI as string, {
dbName: 'doc_gpt'
// @ts-ignore
global.mongodb = 'connecting';
console.log('connect mongo');
try {
// @ts-ignore
global.mongodb = await mongoose.connect(process.env.MONGODB_URI as string, {
dbName: 'doc_gpt',
maxPoolSize: 10,
minPoolSize: 1
});
return cachedClient;
} catch (error) {
console.error('mongo connect error');
// @ts-ignore
global.mongodb = null;
}
}
export * from './models/authCode';

9
src/types/index.d.ts vendored Normal file
View File

@@ -0,0 +1,9 @@
import type { Mongoose } from 'mongoose';
declare global {
interface Global {
mongodb: Mongoose;
}
}
export type a = string;

View File

@@ -19,6 +19,6 @@
"@/*": ["./src/*"]
}
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", "**/*.d.ts"],
"exclude": ["node_modules"]
}