Skip to content

Commit

Permalink
Serialize write access to websocket
Browse files Browse the repository at this point in the history
As the gorilla websocket documentation makes clear, it is the callers
responsibility to ensure there is only 1 concurrent reader and writer to
every websocket.

While investigating alternative Broker implementations which are
asynchronous, I was able to trigger go data race warnings while writing
to the socket from subscriptions which were writing from different
goroutines to the same client.

Add a simple mutex on the websocketPeer to gate writers on Send.
Looking at the current implementation there should only be one reader
from the websocket a time which writes to a messages channel.
  • Loading branch information
yanfali committed Mar 15, 2016
1 parent 679b151 commit c8a26d9
Showing 1 changed file with 4 additions and 0 deletions.
4 changes: 4 additions & 0 deletions websocket.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package turnpike

import (
"fmt"
"sync"
"time"

"github.com/gorilla/websocket"
Expand All @@ -13,6 +14,7 @@ type websocketPeer struct {
messages chan Message
payloadType int
closed bool
writeMutex sync.Mutex
}

// NewWebsocketPeer connects to the websocket server at the specified url.
Expand Down Expand Up @@ -56,6 +58,8 @@ func (ep *websocketPeer) Send(msg Message) error {
if err != nil {
return err
}
ep.writeMutex.Lock()
defer ep.writeMutex.Unlock()
return ep.conn.WriteMessage(ep.payloadType, b)
}
func (ep *websocketPeer) Receive() <-chan Message {
Expand Down

0 comments on commit c8a26d9

Please sign in to comment.