-
Notifications
You must be signed in to change notification settings - Fork 47
/
conn.go
184 lines (160 loc) · 4.2 KB
/
conn.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
package signalflow
import (
"context"
"fmt"
"log"
"net/url"
"path"
"sync"
"time"
"github.com/gorilla/websocket"
)
// How long to wait between connections in case of a bad connection.
var ReconnectDelay = 5 * time.Second
type wsConn struct {
sync.Mutex
ctx context.Context
streamURL *url.URL
outgoingTextMsgs chan *outgoingMessage
incomingTextMsgs chan []byte
incomingBinaryMsgs chan []byte
readErrCh chan error
readCh chan struct{}
connectedCh chan struct{}
ReadTimeout time.Duration
WriteTimeout time.Duration
PostDisconnectCallback func()
PostConnectMessage func() []byte
}
type outgoingMessage struct {
bytes []byte
resultCh chan error
}
func newWebsocketConn(ctx context.Context, streamURL *url.URL) *wsConn {
ws := &wsConn{
ctx: ctx,
streamURL: streamURL,
incomingTextMsgs: make(chan []byte),
incomingBinaryMsgs: make(chan []byte),
outgoingTextMsgs: make(chan *outgoingMessage),
readErrCh: make(chan error),
readCh: make(chan struct{}),
connectedCh: make(chan struct{}),
ReadTimeout: 1 * time.Minute,
WriteTimeout: 20 * time.Second,
}
return ws
}
func (c *wsConn) IncomingTextMessages() <-chan []byte {
return c.incomingTextMsgs
}
func (c *wsConn) IncomingBinaryMessages() <-chan []byte {
return c.incomingBinaryMsgs
}
func (c *wsConn) OutgoingTextMessages() chan<- *outgoingMessage {
return c.outgoingTextMsgs
}
func (c *wsConn) ConnectedSignal() <-chan struct{} {
return c.connectedCh
}
// Run keeps the connection alive and puts all incoming messages into a channel
// as needed.
func (c *wsConn) Run() {
var conn *websocket.Conn
for {
if conn == nil {
// This will get run on before the first connection as well.
if c.PostDisconnectCallback != nil {
c.PostDisconnectCallback()
}
var err error
conn, err = c.connect()
if err != nil {
log.Printf("Error connecting to SignalFlow websocket: %v", err)
time.Sleep(ReconnectDelay)
continue
}
err = c.postConnect(conn)
if err != nil {
log.Printf("Error setting up SignalFlow websocket: %v", err)
conn.Close()
conn = nil
time.Sleep(ReconnectDelay)
continue
}
go c.readNextMessage(conn)
}
select {
case <-c.ctx.Done():
conn.Close()
return
case <-c.readCh:
go c.readNextMessage(conn)
case err := <-c.readErrCh:
log.Printf("Error reading from SignalFlow websocket: %v", err)
conn.Close()
conn = nil
time.Sleep(ReconnectDelay)
case msg := <-c.outgoingTextMsgs:
err := c.writeMessage(conn, msg.bytes)
msg.resultCh <- err
if err != nil {
// Force the connection closed if it isn't already and wait for
// the read goroutine to finish.
conn.Close()
select {
case <-c.readErrCh:
case <-c.readCh:
}
conn = nil
time.Sleep(ReconnectDelay)
}
}
}
}
func (c *wsConn) connect() (*websocket.Conn, error) {
connectURL := *c.streamURL
connectURL.Path = path.Join(c.streamURL.Path, "connect")
conn, _, err := websocket.DefaultDialer.DialContext(c.ctx, connectURL.String(), nil)
if err != nil {
return nil, fmt.Errorf("could not connect Signalflow websocket: %v", err)
}
return conn, nil
}
func (c *wsConn) postConnect(conn *websocket.Conn) error {
if c.PostConnectMessage != nil {
msg := c.PostConnectMessage()
if msg != nil {
return c.writeMessage(conn, msg)
}
}
return nil
}
func (c *wsConn) readNextMessage(conn *websocket.Conn) {
if err := conn.SetReadDeadline(time.Now().Add(c.ReadTimeout)); err != nil {
c.readErrCh <- fmt.Errorf("could not set read timeout in SignalFlow client: %v", err)
return
}
typ, bytes, err := conn.ReadMessage()
if err != nil {
c.readErrCh <- err
return
}
if typ == websocket.TextMessage {
c.incomingTextMsgs <- bytes
} else {
c.incomingBinaryMsgs <- bytes
}
c.readCh <- struct{}{}
}
func (c *wsConn) writeMessage(conn *websocket.Conn, msgBytes []byte) error {
err := conn.SetWriteDeadline(time.Now().Add(c.WriteTimeout))
if err != nil {
return fmt.Errorf("could not set write timeout for SignalFlow request: %v", err)
}
err = conn.WriteMessage(websocket.TextMessage, msgBytes)
if err != nil {
return err
}
return nil
}