uNetworking / uWebSockets.js

μWebSockets for Node.js back-ends :metal:
Apache License 2.0
7.76k stars 563 forks source link

onData not receiving all chunks #921

Closed e3dio closed 1 year ago

e3dio commented 1 year ago

Testing making Posts to server, randomly half the time the Post body is missing the first chunk of data, onData never gets called with the first chunk. Below example:

body = ''; for (let i = 0; i < 50000; i++) body += i + '-';

body.length == 288890;

await fetch('/upload', { method: 'POST', body });
app.post('/upload', async (res, req) => {
   await doAsync(); // update: this caused issue
   const body = await getBody(res, req);
   res.cork(() => res.end('done'));
});

getBody

Result: Body size 256140 != content-length 288890

Looking at console.logs of chunks, it is always missing the first chunk. Issue happens randomly half the time, other times it works

Testing smaller size body that only needs 1 chunk, onData never calls

e3dio commented 1 year ago

I need to test this more I think I did something wrong

e3dio commented 1 year ago

Ok I see, issue was from not immediately attaching res.onData() handler in first synchronous route call, this works now:

app.post('/upload', handle(async (res, req) => {
   res.body = getBody(res, req).catch(e => ({ error: e }));
   await doAsync();
   const body = await res.body;
   !res.ab && res.cork(() => {
      body.error ? res.writeStatus('400').end(body.error) : res.end('done');
   });
}));

I knew this was needed but was not paying attention