Skip to content
This repository was archived by the owner on Sep 2, 2020. It is now read-only.

Commit 0c4e201

Browse files
authored
Merge pull request #7 from ccirello/fix-slack-provider
slack provider: fix race condition when trying to reconnect
2 parents 83a7830 + 5441b6b commit 0c4e201

File tree

1 file changed

+30
-11
lines changed

1 file changed

+30
-11
lines changed

providers/slack.go

Lines changed: 30 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -37,10 +37,11 @@ func init() {
3737
}
3838

3939
type providerSlack struct {
40-
token string
41-
wsURL string
42-
wsConn *websocket.Conn
43-
selfID string
40+
token string
41+
wsURL string
42+
selfID string
43+
wsConnMu sync.Mutex
44+
wsConn *websocket.Conn
4445

4546
in chan messages.Message
4647
out chan messages.Message
@@ -105,7 +106,6 @@ func (p *providerSlack) handshake() {
105106
if !v {
106107
p.err = err
107108
return
108-
109109
}
110110
default:
111111
p.err = err
@@ -126,7 +126,9 @@ func (p *providerSlack) dial() {
126126
p.err = err
127127
return
128128
}
129+
p.wsConnMu.Lock()
129130
p.wsConn = ws
131+
p.wsConnMu.Unlock()
130132
}
131133

132134
func (p *providerSlack) intakeLoop() {
@@ -138,9 +140,15 @@ func (p *providerSlack) intakeLoop() {
138140
UserID string `json:"user"`
139141
Text string `json:"text"`
140142
}
141-
if err := json.NewDecoder(p.wsConn).Decode(&data); err != nil {
143+
144+
p.wsConnMu.Lock()
145+
wsConn := p.wsConn
146+
p.wsConnMu.Unlock()
147+
148+
if err := json.NewDecoder(wsConn).Decode(&data); err != nil {
142149
continue
143150
}
151+
144152
if data.Type != "message" {
145153
continue
146154
}
@@ -219,21 +227,32 @@ func (p *providerSlack) dispatchLoop() {
219227
if len(wsMsg) > 16*1024 {
220228
continue
221229
}
222-
fmt.Fprint(p.wsConn, wsMsg)
230+
231+
p.wsConnMu.Lock()
232+
wsConn := p.wsConn
233+
p.wsConnMu.Unlock()
234+
235+
fmt.Fprint(wsConn, wsMsg)
236+
223237
time.Sleep(1 * time.Second) // https://api.slack.com/docs/rate-limits
224238
}
225239
}
226240

227241
func (p *providerSlack) reconnect() {
228242
for {
229243
time.Sleep(1 * time.Second)
230-
if p.wsConn == nil {
244+
245+
p.wsConnMu.Lock()
246+
wsConn := p.wsConn
247+
p.wsConnMu.Unlock()
248+
249+
if wsConn == nil {
231250
log.Println("slack: cannot reconnect")
232251
break
233252
}
234-
_, err := p.wsConn.Write([]byte(`{"type":"hello"}`))
235-
if err != nil {
236-
log.Println("slack: reconnecting")
253+
254+
if _, err := wsConn.Write([]byte(`{"type":"hello"}`)); err != nil {
255+
log.Printf("slack: reconnecting (%v)", err)
237256
p.handshake()
238257
p.dial()
239258
}

0 commit comments

Comments
 (0)