uNetworking / uWebSockets.js

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

publish/write ordering barrier #422

Closed ronag closed 3 years ago

ronag commented 3 years ago

The documentation currently makes it clear that there are no ordering guarantees between write and publish calls. I assume this is due to performance reasons.

I would like to make a feature request for some kind of barrier function which has a callback that guarantees that all previous writes will be sent before any successive write or publish calls.

e.g.

socket.publish('bar', '123')
socket.flush('bar', () => {
  socket.write('456') // client is guaranteed to receive 123456
})

socket.write('456')
socket.flush(() => {
  socket.publish('foo', '123') // client is guaranteed to receive 123456
})
hst-m commented 3 years ago

if you need guaranteed order between Send to single socket and Publish you could use Publish instead of Send

ws.subscribe(ws.ID)
ws.subscribe('foo')

app.publish(ws.ID,'123')
app.publish('foo','456') // receive 123456

Publishing to single socket topic is some amount less performance than ws.send, I have not tested the difference yet, but it will get you guaranteed ordering without need to mess with "flushing" sockets

ronag commented 3 years ago

Perfect. Thanks!

ronag commented 3 years ago

@hst-m: I assume ordering is guaranteed even between different topics?

hst-m commented 3 years ago

yes can review this description of pub/sub here https://github.com/uNetworking/uWebSockets/issues/939#issuecomment-538802292 "All sets of all triggered Topics are iterated over in order"

I just tried this:

ws.subscribe('1')
ws.subscribe('2')
ws.subscribe('3')

app.publish('3','1')
app.publish('1','2')
app.publish('2','3')
app.publish('1','4')
app.publish('3','5')
app.publish('2','6')
app.publish('1','7')
app.publish('3','8')

and I got '12345678'

Update: order is not guaranteed between different topics