fraudTech commited on
Commit
0bf43c8
Β·
1 Parent(s): d89352c

fixe stop button

Browse files
Files changed (1) hide show
  1. gateway.ts +14 -5
gateway.ts CHANGED
@@ -182,6 +182,9 @@ app.post('/api/chat', apiLimiter, authenticateToken, async (req, res) => {
182
  (req.socket as any)?.setNoDelay?.(true);
183
  res.flushHeaders();
184
 
 
 
 
185
  // Forward request to backend with streaming
186
  const response = await axios.post(`${BACKEND_URL}/api/chat`, {
187
  message,
@@ -196,7 +199,8 @@ app.post('/api/chat', apiLimiter, authenticateToken, async (req, res) => {
196
  ...(HF_TOKEN && { 'Authorization': `Bearer ${HF_TOKEN}` }),
197
  ...(BACKEND_API_SECRET && { 'X-API-Key': BACKEND_API_SECRET })
198
  },
199
- responseType: 'stream'
 
200
  });
201
 
202
  // Pipe the stream from backend to frontend
@@ -205,12 +209,17 @@ app.post('/api/chat', apiLimiter, authenticateToken, async (req, res) => {
205
  // Handle errors in the stream
206
  response.data.on('error', (error: any) => {
207
  console.error('❌ Stream error:', error.message);
208
- res.end();
209
  });
210
 
211
- // Clean up when client disconnects
212
- req.on('close', () => {
213
- response.data.destroy();
 
 
 
 
 
214
  });
215
 
216
  } catch (error: any) {
 
182
  (req.socket as any)?.setNoDelay?.(true);
183
  res.flushHeaders();
184
 
185
+ // AbortController to cancel the outgoing axios request when the client disconnects
186
+ const axiosAbort = new AbortController();
187
+
188
  // Forward request to backend with streaming
189
  const response = await axios.post(`${BACKEND_URL}/api/chat`, {
190
  message,
 
199
  ...(HF_TOKEN && { 'Authorization': `Bearer ${HF_TOKEN}` }),
200
  ...(BACKEND_API_SECRET && { 'X-API-Key': BACKEND_API_SECRET })
201
  },
202
+ responseType: 'stream',
203
+ signal: axiosAbort.signal,
204
  });
205
 
206
  // Pipe the stream from backend to frontend
 
209
  // Handle errors in the stream
210
  response.data.on('error', (error: any) => {
211
  console.error('❌ Stream error:', error.message);
212
+ if (!res.writableEnded) res.end();
213
  });
214
 
215
+ // Detect when the frontend client disconnects (res.on('close') fires on true
216
+ // disconnect; req.on('close') fires too early β€” when request body is consumed).
217
+ res.on('close', () => {
218
+ if (!res.writableEnded) {
219
+ console.log('πŸ›‘ Frontend disconnected β€” cancelling backend request');
220
+ axiosAbort.abort(); // cancel the outgoing HTTP request to backend
221
+ response.data.destroy(); // destroy the readable stream
222
+ }
223
  });
224
 
225
  } catch (error: any) {