-
Notifications
You must be signed in to change notification settings - Fork 3
/
transport.go
185 lines (166 loc) · 3.86 KB
/
transport.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
package websocket
import (
"context"
"crypto/tls"
"encoding/json"
"fmt"
"github.com/op/go-logging"
"net"
"net/http"
"sync"
"time"
"github.com/gorilla/websocket"
)
const WS_WRITE_CAPACITY = 100
func newWs(baseURL string, logTransport bool, log *logging.Logger) *ws {
return &ws{
BaseURL: baseURL,
downstream: make(chan []byte),
quit: make(chan error),
logTransport: logTransport,
log: log,
lock: &sync.RWMutex{},
createTime: time.Now(),
writeChan: make(chan []byte, WS_WRITE_CAPACITY),
}
}
type ws struct {
ws *websocket.Conn
lock *sync.RWMutex
BaseURL string
TLSSkipVerify bool
downstream chan []byte
logTransport bool
log *logging.Logger
createTime time.Time
writeChan chan []byte
quit chan error // signal to parent with error, if applicable
}
func (w *ws) Connect() error {
if w.ws != nil {
return nil // no op
}
var d = websocket.Dialer{
Subprotocols: []string{"p1", "p2"},
ReadBufferSize: 1024,
WriteBufferSize: 1024,
Proxy: http.ProxyFromEnvironment,
}
d.TLSClientConfig = &tls.Config{InsecureSkipVerify: w.TLSSkipVerify}
w.log.Info("connecting ws to %s", w.BaseURL)
ws, resp, err := d.Dial(w.BaseURL, nil)
if err != nil {
if err == websocket.ErrBadHandshake {
w.log.Errorf("bad handshake: status code %d", resp.StatusCode)
}
return err
}
w.ws = ws
go w.listenWriteChannel()
go w.listenWs()
return nil
}
// Send marshals the given interface and then sends it to the API. This method
// can block so specify a context with timeout if you don't want to wait for too
// long.
func (w *ws) Send(ctx context.Context, msg interface{}) error {
if w.ws == nil {
return ErrWSNotConnected
}
bs, err := json.Marshal(msg)
if err != nil {
return err
}
select {
case <- ctx.Done():
return ctx.Err()
case <- w.quit: // ws closed
return fmt.Errorf("websocket connection closed")
default:
}
w.log.Debug("ws->srv: %s", string(bs))
// push request into writer channel
w.writeChan <- bs
if err != nil {
return err
}
return nil
}
func (w *ws) Done() <-chan error {
return w.quit
}
// listen for write requests and perform them
func (w *ws) listenWriteChannel() {
for {
select {
case <- w.quit: // ws closed
return
case message := <- w.writeChan:
wsWriter, err := w.ws.NextWriter(websocket.TextMessage)
if err != nil {
w.log.Error("Unable to provision ws connection writer: ", err)
w.stop(err)
return
}
_, err = wsWriter.Write(message)
if err != nil {
w.log.Error("Unable to write to ws: ", err)
w.stop(err)
return
}
if err := wsWriter.Close(); err != nil {
w.log.Error("Unable to close ws connection writer: ", err)
w.stop(err)
return
}
}
}
}
// listen on ws & fwd to listen()
func (w *ws) listenWs() {
for {
if w.ws == nil {
return
}
select {
case <-w.quit: // ws connection ended
return
default:
_, msg, err := w.ws.ReadMessage()
if err != nil {
if cl, ok := err.(*websocket.CloseError); ok {
w.log.Errorf("close error code: %d", cl.Code)
}
// a read during normal shutdown results in an OpError: op on closed connection
if _, ok := err.(*net.OpError); ok {
// general read error on a closed network connection, OK
return
}
w.stop(err)
return
}
w.log.Debugf("srv->ws: %s", string(msg))
w.downstream <- msg
}
}
}
func (w *ws) Listen() <-chan []byte {
return w.downstream
}
func (w *ws) stop(err error) {
w.lock.Lock()
defer w.lock.Unlock()
if w.ws != nil {
w.quit <- err // pass error back
close(w.quit) // signal to parent listeners
close(w.downstream)
if err := w.ws.Close(); err != nil {
panic(fmt.Errorf("error closing websocket: %s", err))
}
w.ws = nil
}
}
// Close the websocket connection
func (w *ws) Close() {
w.stop(fmt.Errorf("transport connection Close called"))
}