unjs / nitro

Next Generation Server Toolkit. Create web servers with everything you need and deploy them wherever you prefer.
https://nitro.unjs.io
MIT License
6.1k stars 502 forks source link

Difficulty Detecting Aborted Streaming Request on Nitro Side #2118

Open XStarlink opened 9 months ago

XStarlink commented 9 months ago

Environment

Nitro: 2.8.1 Node: 18

Reproduction

https://stackblitz.com/edit/nuxt-tip-cancel-fetch-request-ysnjhe?file=app.vue,components%2FFetchStream.vue

Describe the bug

Hello Nitro Team,

Thanks for the incredible work you're doing with Nuxt and Nitro!

I'm currently facing a challenge, I'm trying to detect on the Nitro side when a request has been aborted or closed, specifically in the case of a streaming request. I've tried numerous approaches, but I haven't been successful in detecting a request being aborted on the Nitro side to halt the execution of the event handler and avoid further processing.

I've created a small reproduction for you to take a look at here

I thank you very much for your help, and I wish you an excellent day!

Additional context

No response

Logs

No response

goetzrobin commented 3 months ago

@XStarlink did you ever find a solution for this? @pi0 I think a common use case is to stop the generation of an AI, e.g. through the OpenAI API, response whenever the request to a Nitro is aborted. However, something like res.req.on('close', () => console.log('closed')) seems to never fire even if the frontend request is aborted

XStarlink commented 3 months ago

@goetzrobin Yes there was an issue in nitro, look at this discussion but now if you are in the latest Nuxt version, you can use this code in your server route:

event.node.res.on('close', () => {
  console.log('Connection closed by client');
});

I've updated the Stackblitz example linked to this issue to show you, but apparently your project must be running on a node server to use the code snippet above otherwise it won't detect that the connection is closed.

For other environments, I don't know how to detect this, but if someone can answer this question, it would be very interesting.