Fix race condition in RenderSocket #105
Open
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Socket.currentRenderwas read and written from multiple goroutines (WebSocket reader, broadcast handler, upload POST handler) without synchronization. The render, diff, send, and update steps are also not atomic — a concurrent event can interleave between diffing and updating the stored render tree, producing corrupt patches.The same applies to
Socket.uploadsandSocket.uploadConfigs, which are accessed from both the HTTP POST upload handler and WebSocket event handlers concurrently.I added a new test,
socket_race_test.go, which triggers the race detector.I took the simple approach for the fix, which was to introduce a mutex to protect both the render and upload state.
I added
Socket.Render(ctx)which is the replacement forRenderSocket, using the mutex to synchronize the render->diff->patch cycle.A more controversial change might be that I changed
RenderSocket,UpdateRender, andLatestRenderto be un-exported, so that an outside caller can't do the wrong thing accidentally.I also changed
UploadConfigsandUploadsto return copies so the caller can't mess with the slice that might be concurrently changed byAssignUpload/ClearUpload/etc