Falldot / esbuild-dev-server

This plugin allows you to start a local server with hot reloading with Esbuild
MIT License
48 stars 1 forks source link

hot reload intermittently fails #6

Open eyeree opened 2 years ago

eyeree commented 2 years ago

Occasionally evt.Data is 'reload\nreload' instead of just 'reload', causing the console.error branch to be taken in the reload script. I'll see 3-4 successful reloads, then 1-2 failed reloads, then a few successful, etc.

I'm using the linux-x64 server running on Unbuntu under Windows 10 using WSL 2.0. I see the behavior in Chrome, Firefox, and Edge running under Windows on the same host.

It's hard to tell, but it might be happening more often if I have Chrome, Firefox, and Edge all open at the same time, vs. just one of them. When I do have more than one browser open, they ALMOST always either succeed or fail together, but occasional one will work while the others fail.

Seems like race condition of some sort. Wouldn't be noticeable if the reload script ignored the value.

jaens commented 2 years ago

This is caused by the following code, which for some mysterious reason racily[^1] reads all still pending messages from the websocket's broadcast channel and separates them with \n:

https://github.com/Falldot/esbuild-dev-server/blob/eab36f97359b74354af19c25fa9c4e8971ec0e3f/internal/ws/client.go#L85-L89

In this case, what's happening is that there are two consecutive reload messages in the channel which then cause this corruption.

[^1]: Note that len(c.send) can further increase due to new messages while in the for loop.

WebSocket messages are supposed to be atomic units, so not sure why that code even exists - and in any case, it's impossible to implement message merging correctly (ie. non-racily) with that code (or basically, with any implementation that uses a single raw byte[] channel - for multi-part messages, the channel needs to either be framed with message lengths or use a terminator).