uWebSockets.js opens with one ID but closes with other ID

148 views Asked by At

I'm using Bun + Elysia and they are using uWebSockets.js. I use Postman to test, when i make connection it opens with one id number but when i close it closes with other ID number.

Should the ID's be the same?

export const ws = new Elysia().ws('/ws', {
  body: t.Object({
    message: t.String(),
  }),
  open: (ws) => {
    console.log(' ~ open:', ws.id);
  },
  message: (ws) => {
    console.log(' ~ message:', ws.id);
  },
  close: (ws) => {
    console.log(' ~ close:', ws.id);
  },
  error: (c) => {
    console.log(' ~ error:', JSON.stringify(c));
  },
});

enter image description here

1

There are 1 answers

0
Kitanga Nday On

So I've handed in an PR to fix this issues, but a solution for now looks like this:

open(ws) {
    // ws.raw.id = ws.id
    ws.raw.id = ws.id = crypto.randomInt()
    console.log('Open ID:', ws.raw.id)
},
close(ws) {
    console.log('Close ID:', ws.raw.id)
}

This works because uWebSockets (the underlaying websockets library used by Bunjs and Elysiajs) hands in the correct websocket for the close callback. Elysia stores this in the raw prop.

EDIT: Almost forgot, for the ID, use crypto.randomInt(), Elysia's using Date.now(), which is bad for randomness, I already tested, if you are creating a lot of connections, Date.now() performs extremely poorly. In my test, out of 100 iterations I only had 2 unique IDs.

PR: https://github.com/elysiajs/elysia/issues/381