Skip to content

Commit 1c8b1c1

Browse files
committed
fix stability issue with request already being closed
1 parent 6b2934d commit 1c8b1c1

File tree

1 file changed

+18
-14
lines changed

1 file changed

+18
-14
lines changed

routes/completionsRoutes.js

Lines changed: 18 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -183,19 +183,22 @@ router.post('/', async (req, res) => {
183183

184184
const onClose = () => {
185185
global.serverBusy = false;
186-
global.childProcess.kill('SIGINT');
187186
console.log('Request DONE');
188-
res
189-
.status(200)
190-
.json(
191-
dataToCompletionResponse(
192-
responseContent.trim(),
193-
promptTokens,
194-
completionTokens,
195-
'stop'
196-
)
197-
);
198-
res.end()
187+
if (!res.headersSent) {
188+
res
189+
.status(200)
190+
.json(
191+
dataToCompletionResponse(
192+
responseContent.trim(),
193+
promptTokens,
194+
completionTokens,
195+
'stop'
196+
)
197+
);
198+
res.end();
199+
} else {
200+
!res.writableEnded && res.end();
201+
}
199202
global.lastRequest = {
200203
type: 'completion',
201204
prompt: prompt,
@@ -205,6 +208,7 @@ router.post('/', async (req, res) => {
205208
!!debounceTimer && clearTimeout(debounceTimer);
206209
console.log('Readable Stream: CLOSED');
207210
controller.close();
211+
global.childProcess.kill('SIGINT');
208212
};
209213

210214
const onError = (error) => {
@@ -244,7 +248,6 @@ router.post('/', async (req, res) => {
244248
stopPrompts.includes(last2Content) ||
245249
completionTokens >= maxTokens - 1
246250
) {
247-
global.childProcess.kill('SIGINT');
248251
console.log('Request DONE');
249252
res.write('event: data\n');
250253
res.write(
@@ -267,6 +270,7 @@ router.post('/', async (req, res) => {
267270
global.serverBusy = false;
268271
stdoutStream.removeAllListeners();
269272
clearTimeout(debounceTimer);
273+
global.childProcess.kill('SIGINT');
270274
} else {
271275
res.write('event: data\n');
272276
res.write(`data: ${JSON.stringify(chunk)}\n\n`);
@@ -305,7 +309,6 @@ router.post('/', async (req, res) => {
305309
stopPrompts.includes(last2Content) ||
306310
completionTokens >= maxTokens - 1
307311
) {
308-
global.childProcess.kill('SIGINT');
309312
console.log('Request DONE');
310313
res
311314
.status(200)
@@ -325,6 +328,7 @@ router.post('/', async (req, res) => {
325328
global.serverBusy = false;
326329
stdoutStream.removeAllListeners();
327330
clearTimeout(debounceTimer);
331+
global.childProcess.kill('SIGINT');
328332
} else {
329333
responseContent += currContent;
330334
lastChunk = chunk;

0 commit comments

Comments
 (0)