-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
305 lines (251 loc) · 7.52 KB
/
client.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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
package eventedconnection
import (
"crypto/tls"
"errors"
"net"
"sync"
"time"
)
// Client gives us a stable way to connect and maintain a connection to a TCP endpoint.
// Client broadcasts 2 separate events via closing a channel: Connected and Disconnected.
// This allows any number of downstream consumers to be informed when a state change happens.
type Client struct {
Read chan *[]byte
Disconnected chan struct{}
Connected chan struct{}
c net.Conn
connectionTimeout time.Duration
readTimeout time.Duration
writeTimeout time.Duration
endpoint string
readBufferSize int
afterReadHook AfterReadHook
afterConnectHook AfterConnectHook
beforeDisconnectHook BeforeDisconnectHook
onErrorHook OnErrorHook
useTLS bool
tlsConfig *tls.Config
closer sync.Once
starter sync.Once
mutex *sync.RWMutex // allows for using this connection in multiple goroutines
}
func (conn *Client) setDefaults() {
if conn.connectionTimeout == 0*time.Second { // default timeout for connecting
conn.connectionTimeout = DefaultConnectionTimeout
}
if conn.readTimeout == 0*time.Second { // default timeout for connecting
conn.readTimeout = DefaultReadTimeout
}
if conn.writeTimeout == 0*time.Second { // default timeout for connecting
conn.writeTimeout = DefaultWriteTimeout
}
if conn.readBufferSize == 0 {
conn.readBufferSize = DefaultReadBufferSize
}
if conn.afterReadHook == nil {
conn.afterReadHook = defaultAfterReadHook
}
if conn.onErrorHook == nil {
conn.onErrorHook = defaultOnErrorHook
}
}
// NewClient is the Connection constructor.
func NewClient(conf *Config) (*Client, error) {
if len(conf.Endpoint) == 0 {
return nil, errors.New("invalid endpoint (empty string)")
}
conn := Client{
endpoint: conf.Endpoint,
connectionTimeout: conf.ConnectionTimeout,
readTimeout: conf.ReadTimeout,
writeTimeout: conf.WriteTimeout,
readBufferSize: conf.ReadBufferSize,
afterReadHook: conf.AfterReadHook,
afterConnectHook: conf.AfterConnectHook,
beforeDisconnectHook: conf.BeforeDisconnectHook,
onErrorHook: conf.OnErrorHook,
Disconnected: make(chan struct{}),
Connected: make(chan struct{}),
Read: make(chan *[]byte, 4), // 4 packets (up to 4 * conn.ReadBufferSize); reduces blocking when reading from connection
mutex: &sync.RWMutex{},
}
if conf.UseTLS {
conn.tlsConfig = conf.TLSConfig
conn.useTLS = conf.UseTLS
}
conn.setDefaults()
return &conn, nil
}
// Connect attempts to establish a TCP connection to conn.Endpoint.
func (conn *Client) Connect() error {
var err error
var connection net.Conn
conn.starter.Do(func() {
if conn.useTLS {
connection, err = tls.Dial("tcp", conn.endpoint, conn.tlsConfig)
} else {
connection, err = net.DialTimeout("tcp", conn.endpoint, conn.connectionTimeout)
}
if err != nil {
conn.onErrorHook(err)
return // return early so we don't execute other hooks, send Connected event, etc.
}
conn.setConnection(connection)
defer conn.afterConnect()
go conn.readFromConn()
close(conn.Connected) // broadcast that TCP connection to interface was established
})
return err
}
func (conn *Client) Reconnect() error {
conn.Close()
conn.reset()
return conn.Connect()
}
func (conn *Client) reset() {
conn.mutex.Lock()
defer conn.mutex.Unlock()
conn.Disconnected = make(chan struct{})
conn.Connected = make(chan struct{})
conn.starter = sync.Once{}
conn.closer = sync.Once{}
}
func (conn *Client) setConnection(c net.Conn) {
conn.mutex.Lock()
conn.c = c
conn.mutex.Unlock()
}
func (conn *Client) afterConnect() {
if conn.afterConnectHook != nil {
err := conn.afterConnectHook()
if err != nil {
conn.onErrorHook(err)
}
}
}
// IsActive provides a way to check if the connection is still usable
func (conn *Client) IsActive() bool {
conn.mutex.RLock()
defer conn.mutex.RUnlock()
return conn.c != nil
}
// Write provides a thread-safe way to send messages to the endpoint. If the connection is
// nil (e.g. closed) then this is a noop.
func (conn *Client) Write(data *[]byte) error {
var err error
connection := conn.rawConnection()
if connection == nil {
err = errors.New("called Write with nil connection")
conn.onErrorHook(err)
return err
}
err = connection.SetWriteDeadline(time.Now().Add(conn.GetWriteTimeout()))
if err != nil {
conn.onErrorHook(err)
defer conn.Close()
return err
}
_, err = connection.Write(*data)
if err != nil {
conn.onErrorHook(err)
defer conn.Close()
}
return err
}
// Close closes the TCP connection. Broadcasts via the Disconnected channel.
// Safe to call more than once, however will only close an open TCP connection on the first call.
// Closes the conn.Disconnected chan prior to closing the TCP connection to allow
// short-circuiting of downstream `select` blocks and avoid attempts to write to it
// by the caller.
func (conn *Client) Close() {
conn.mutex.Lock()
defer conn.mutex.Unlock()
conn.closer.Do(func() {
if conn.beforeDisconnectHook != nil {
if err := conn.beforeDisconnectHook(); err != nil {
conn.onErrorHook(err)
}
}
close(conn.Disconnected) // broadcast that TCP connection to interface was closed
if conn.c != nil {
conn.c.Close()
conn.c = nil // set C to nil so it's clear the connection cannot be used
}
})
}
// Disconnect is an alias for conn.Close()
func (conn *Client) Disconnect() {
conn.Close()
}
// processResponse handles data coming from the TCP connection
// and sends it through the conn.Read chan
func (conn *Client) processResponse(data []byte) (err error) {
var processed []byte
if len(data) > 0 {
processed, err = conn.afterReadHook(data)
if err != nil {
conn.onErrorHook(err)
}
conn.Read <- &processed
}
return err
}
// readFromConn reads data from the connection into a buffer and then
// passes onto processResponse. In the event of an error the connection
// is closed.
func (conn *Client) readFromConn() error {
defer conn.Close()
buffer := make([]byte, conn.GetReadBufferSize())
for {
var err error
connection := conn.rawConnection()
if connection == nil {
err = errors.New("unable to read from nil connection")
conn.onErrorHook(err)
return err
}
err = connection.SetReadDeadline(time.Now().Add(conn.GetReadTimeout()))
if err != nil {
conn.onErrorHook(err)
return err
}
numBytesRead, err := connection.Read(buffer)
if numBytesRead > 0 {
res := make([]byte, numBytesRead)
// Copy the buffer so it's safe to pass along
copy(res, buffer[:numBytesRead])
err = conn.processResponse(res)
}
if err != nil {
conn.onErrorHook(err)
return err
}
}
}
// rawConnection is used for getting the underlying TCP connection
// in a thread safe way
func (conn *Client) rawConnection() net.Conn {
conn.mutex.RLock()
defer conn.mutex.RUnlock()
return conn.c
}
// GetEndpoint returns the value of conn.endpoint
func (conn *Client) GetEndpoint() string {
return conn.endpoint
}
// GetReadBufferSize returns the value of conn.readBufferSize
func (conn *Client) GetReadBufferSize() int {
return conn.readBufferSize
}
// GetWriteTimeout returns the value of conn.writeTimeout
func (conn *Client) GetWriteTimeout() time.Duration {
return conn.writeTimeout
}
// GetReadTimeout returns the value of conn.readTimeout
func (conn *Client) GetReadTimeout() time.Duration {
return conn.readTimeout
}
// GetConnectionTimeout returns the value of conn.connectionTimeout
func (conn *Client) GetConnectionTimeout() time.Duration {
return conn.connectionTimeout
}