forked from potato2003/actioncable-client-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
connection.go
231 lines (197 loc) · 4.84 KB
/
connection.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
package actioncable
import (
"errors"
"log"
"net/http"
"sync"
"time"
"github.com/gorilla/websocket"
"github.com/jpillora/backoff"
)
const (
// use the same value as actioncable.js
// 1 ping is 2 sec interval, so detect stale when 2 ping missing.
DEFAULT_STALE_THRESHOLD time.Duration = 6 * time.Second
)
var (
staleError error = errors.New("connection is stale")
)
type connection struct {
url string
consumer *Consumer
subscriptions *Subscriptions
disconnected bool
dialer *websocket.Dialer
ws *websocket.Conn
header *http.Header
recieveCh chan Event
isReady bool
readyCh chan struct{}
stopCh chan struct{}
pingedAt time.Time
connectedAt time.Time
lockForSend *sync.Mutex
}
func newConnection(url string) *connection {
return &connection{
url: url,
disconnected: true,
dialer: &websocket.Dialer{
HandshakeTimeout: 5 * time.Second,
},
header: &http.Header{},
recieveCh: make(chan Event, 1),
isReady: false,
readyCh: make(chan struct{}, 1),
lockForSend: new(sync.Mutex),
}
}
func (c *connection) start() {
c.stopCh = make(chan struct{}, 1)
go c.connectionLoop()
c.waitUntilReady()
}
func (c *connection) stop() error {
c.ws.Close()
c.stopCh <- struct{}{}
return nil
}
func (c *connection) connectionLoop() {
b := backoff.Backoff{
Min: 100 * time.Millisecond,
Max: 5000 * time.Millisecond,
Factor: 3,
Jitter: true,
}
defer func() {
c.ws.Close()
}()
/*
Connect to actioncable server.
If it fails, will retry to connect with backoff.
After connection establishment, continuously receive messages
from server, and notify to event handler.
*/
RECONNECT_LOOP:
for {
c.isReady = false
err := c.establishConnection()
if err != nil {
logger.Infof("failed to connect, %s\n", err)
} else {
b.Reset() // reset the backoff delay when connection established
c.eventHandlerLoop()
}
select {
case <-c.stopCh:
break RECONNECT_LOOP
case <-time.After(b.Duration()): // exponential backoff
logger.Infof("reconnecting")
}
}
return
}
func (c *connection) establishConnection() error {
ws, _, err := c.dialer.Dial(c.url, *c.header)
if err != nil {
return err
}
c.ws = ws
return nil
}
func (c *connection) eventHandlerLoop() {
for {
event, err := c.receive() // wait max `DEFAULT_STALE_THRESHOLD` sec until recive new message
if err != nil {
se := createSubscriptionEvent("disconnected", nil)
c.subscriptions.notifyAll(se)
logger.Errorf("%s\n", err)
return // attempts to reconnect
}
switch event.Type {
case "ping": // receive every 2 sec
c.recordPing()
case "welcome": // receive after establish connection
logger.Debug("Received welcome message")
c.recordConnect()
c.subscriptions.reload()
c.ready()
case "confirm_subscription": // response of subscribe request
logger.Debug("Received confirm_subscription message")
se := createSubscriptionEvent(Connected, event)
c.subscriptions.notify(event.Identifier, se)
case "rejection":
c.subscriptions.reject(event.Identifier)
case "reject_subscription":
se := createSubscriptionEvent(Rejected, event)
c.subscriptions.notify(event.Identifier, se)
case "disconnect":
// close
se := createSubscriptionEvent(Disconnected, nil)
c.subscriptions.notifyAll(se)
return
default:
se := createSubscriptionEvent(Received, event)
c.subscriptions.notify(event.Identifier, se)
}
}
}
func (c *connection) receive() (*Event, error) {
// Note to not call receive() in concurrent, it's not working.
// because, gorilla/websocket does not support concurrent reading.
// see: https://godoc.org/github.com/gorilla/websocket#hdr-Concurrency
ch := make(chan *Event)
errCh := make(chan error)
go func() {
event := &Event{}
if err := c.ws.ReadJSON(event); err != nil {
errCh <- err
}
ch <- event
}()
// using timeout for checking stale of ac server.
select {
case event := <-ch:
return event, nil
case err := <-errCh:
return nil, err
case <-time.After(DEFAULT_STALE_THRESHOLD):
log.Printf("connection is stale")
return nil, staleError
}
return nil, nil
}
func (c *connection) send(data map[string]interface{}) error {
// gorilla/websocket does not support concurrent writing.
// see: https://godoc.org/github.com/gorilla/websocket#hdr-Concurrency
c.lockForSend.Lock()
defer c.lockForSend.Unlock()
err := c.ws.WriteJSON(data)
if err != nil {
log.Println(err)
return err
}
return nil
}
func (c *connection) ready() {
c.isReady = true
clearCh(c.readyCh)
c.readyCh <- struct{}{}
}
func (c *connection) waitUntilReady() {
if !c.isReady {
_ = <-c.readyCh
}
}
func (c *connection) recordPing() {
c.pingedAt = time.Now()
}
func (c *connection) recordConnect() {
c.recordPing()
c.connectedAt = time.Now()
}
func clearCh(ch chan struct{}) {
for len(ch) > 0 {
_ = <-ch
}
}