second-state / wasmedge-quickjs

A high-performance, secure, extensible, and OCI-complaint JavaScript runtime for WasmEdge.
Apache License 2.0
477 stars 59 forks source link

Http connection ends after async operation in Express #131

Open lastmjs opened 7 months ago

lastmjs commented 7 months ago

This bug was a bit difficult to track down. Essentially in Express.js if you use the text or json body parser middleware, and you have an asynchronous operation in your middleware callback before responding, you will never respond.

I've tracked it down to right here: https://github.com/second-state/wasmedge-quickjs/blob/main/modules/http.js#L565

I've commented out that code in my own fork. It seems that because the stream is auto destroyed, this happens perhaps in the next tick or something after being completely read, thus when the promise returns the http connection has been ended...maybe it's something with how I have my event loop setup? I think I have it pretty good though, I execute a function, poll the promises, then execute macro tasks and immediately poll promises after each tick task execution until there are no more macro tasks.

Here's an example similar to what did not work before commenting out that code:

app.use(express.text());

app.post('/', async (req, res) => {
  await test();
  res.send('Finished');
});

async test() {
  console.log('test');
}

If your request has the content type set appropriately to text/plain then this request will never finish.