Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 7 additions & 7 deletions api/stream/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ type client struct {
conn *websocket.Conn
onClose func(*client)
write chan *model.MessageExternal
closed chan struct{}
userID uint
token string
once once
Expand All @@ -33,6 +34,7 @@ func newClient(conn *websocket.Conn, userID uint, token string, onClose func(*cl
return &client{
conn: conn,
write: make(chan *model.MessageExternal, 1),
closed: make(chan struct{}),
userID: userID,
token: token,
onClose: onClose,
Expand All @@ -43,15 +45,15 @@ func newClient(conn *websocket.Conn, userID uint, token string, onClose func(*cl
func (c *client) Close() {
c.once.Do(func() {
c.conn.Close()
close(c.write)
close(c.closed)
})
}

// NotifyClose closes the connection and notifies that the connection was closed.
func (c *client) NotifyClose() {
c.once.Do(func() {
c.conn.Close()
close(c.write)
close(c.closed)
c.onClose(c)
})
}
Expand Down Expand Up @@ -87,11 +89,9 @@ func (c *client) startWriteHandler(pingPeriod time.Duration) {

for {
select {
case message, ok := <-c.write:
if !ok {
return
}

case <-c.closed:
return
case message := <-c.write:
c.conn.SetWriteDeadline(time.Now().Add(writeWait))
if err := writeJSON(c.conn, message); err != nil {
printWebSocketError("WriteError", err)
Expand Down
5 changes: 4 additions & 1 deletion api/stream/stream.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,10 @@ func (a *API) Notify(userID uint, msg *model.MessageExternal) {
defer a.lock.RUnlock()
if clients, ok := a.clients[userID]; ok {
for _, c := range clients {
c.write <- msg
select {
case c.write <- msg:
case <-c.closed:
}
}
}
}
Expand Down
18 changes: 18 additions & 0 deletions api/stream/stream_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,24 @@ func TestWritePingFails(t *testing.T) {
user.expectNoMessage()
}

func TestNotifyDoesNotPanicWhenClientIsClosed(t *testing.T) {
mode.Set(mode.TestDev)
defer leaktest.Check(t)()

server, api := bootTestServer(staticUserID())
defer server.Close()
defer api.Close()

ws, _, err := websocket.DefaultDialer.Dial(wsURL(server.URL), nil)
assert.Nil(t, err)
defer ws.Close()

waitForConnectedClients(api, 1)

clients(api, 1)[0].Close()
api.Notify(1, &model.MessageExternal{Message: "after close"})
}

func TestPing(t *testing.T) {
mode.Set(mode.TestDev)

Expand Down
Loading