-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconn.go
336 lines (271 loc) · 6.85 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
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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
package skytable
import (
"context"
"fmt"
"net"
"strings"
"time"
"github.com/No3371/go-skytable/protocol"
"github.com/No3371/go-skytable/response"
)
type Conn struct {
openedAt time.Time
usedAt time.Time
netConn net.Conn
strBuilder *strings.Builder
respReader *response.ResponseReader
autoReconnect bool
closed chan struct{}
err error
}
func (c Conn) OpenedAt () time.Time {
return c.openedAt
}
func (c Conn) UsedAt () time.Time {
return c.usedAt
}
func (c *Conn) Close() {
close(c.closed)
c.netConn.Close()
}
func (c *Conn) errClose(err error) {
c.err = err
c.Close()
}
// A Conn may closes itself when errors occured when reading/writng packets.
//
// While all the errors are being returned and can be handled, enabling auto reconnection will save you the trouble dealing with disconnection
//
// ⚠️ This could make you unaware of issues.
func (c *Conn) EnableAutoReconnect() {
c.autoReconnect = true
}
// Err() return an error if the conn is closed due to an error
func (c *Conn) Err() error {
return c.err
}
func (c *Conn) reconnect () error {
nc, err := net.DialTCP("tcp", nil, c.netConn.RemoteAddr().(*net.TCPAddr))
if err != nil {
return err
}
c.strBuilder.Reset()
c.closed = make(chan struct{})
c.openedAt = time.Now()
c.usedAt = time.Now()
c.err = nil
c.netConn = nc
pv, err := c.SysInfoProtocol(context.Background())
if err != nil {
return fmt.Errorf("conn: failed to get protocol version: %w", err)
}
if pv != ProtoVer {
return protocol.ErrProtocolVersion
}
return nil
}
func (c *Conn) checkClosed () error {
select {
case <-c.closed:
if c.autoReconnect {
err := c.reconnect()
if err != nil {
return fmt.Errorf("failed to reconnect: %w (previous: %s)", err, c.err)
}
return nil
} else {
return NewUsageError("the conn is already closed.", c.err)
}
default:
return nil
}
}
// Create a new Conn.
// If auth is enabled on the destination server, use [NewConnAuth] instead.
//
// After connection established, the driver automatically validate Skyhash protocol version with the server,
// and return an error in case of mismatch.
func NewConn(remote *net.TCPAddr) (*Conn, error) {
nc, err := net.DialTCP("tcp", nil, remote)
if err != nil {
return nil, err
}
conn := &Conn{
openedAt: time.Now(),
usedAt: time.Now(),
netConn: nc,
strBuilder: &strings.Builder{},
respReader: response.NewResponseReader(),
closed: make(chan struct{}),
}
pv, err := conn.SysInfoProtocol(context.Background())
if err != nil {
return nil, fmt.Errorf("conn: failed to get protocol version: %w", err)
}
if pv != ProtoVer {
return nil, protocol.ErrProtocolVersion
}
return conn, nil
}
// Create a new Conn and ``AUTH LOGIN'' with the provided auth info.
//
// After connection established, the driver automatically
// validate Skyhash protocol version with the server,
// and return an error in case of mismatch.
func NewConnAuth(remote *net.TCPAddr, authProvider AuthProvider) (*Conn, error) {
nc, err := net.DialTCP("tcp", nil, remote)
if err != nil {
return nil, err
}
conn := &Conn{
openedAt: time.Now(),
usedAt: time.Now(),
netConn: nc,
strBuilder: &strings.Builder{},
respReader: response.NewResponseReader(),
closed: make(chan struct{}),
}
if authProvider != nil {
err = conn.AuthLogin(context.Background(), authProvider)
if err != nil {
return nil, fmt.Errorf("conn pool: conn: failed to auth login: %w", err)
}
}
pv, err := conn.SysInfoProtocol(context.Background())
if err != nil {
return nil, fmt.Errorf("conn: failed to get protocol version: %w", err)
}
if pv != ProtoVer {
return nil, protocol.ErrProtocolVersion
}
return conn, nil
}
// Allows building a packet easily like:
// c.BuildSingleActionPacketRaw("SET", "X", 100)
//
// The arguments accept any type. The arguments are formatted internally with %v so most basic types should be supported.
func (c *Conn) BuildSingleActionPacketRaw(segs []any) (raw string, err error) {
c.strBuilder.Reset()
_, err = fmt.Fprint(c.strBuilder, "*1\n")
if err != nil {
return "", err
}
err = c.appendSingleActionRaw(segs)
if err != nil {
return "", err
}
return c.strBuilder.String(), nil
}
func (c *Conn) appendSingleActionRaw(segs []any) (err error) {
_, err = fmt.Fprintf(c.strBuilder, "~%d\n", len(segs))
if err != nil {
return err
}
for _, s := range segs {
str := fmt.Sprintf("%v", s)
_, err = fmt.Fprintf(c.strBuilder, "%d\n%s\n", len(str), str)
if err != nil {
return err
}
}
return nil
}
func (c *Conn) ExecRaw(query string) (*RawResponsePacket, error) {
if err := c.checkClosed(); err != nil {
return nil, err
}
_, err := c.netConn.Write([]byte(query))
if err != nil {
c.errClose(err)
return nil, NewComuError("failed to write to conn", err)
}
resps, err := c.respReader.Read(c.netConn)
if err != nil {
c.errClose(err)
return nil, NewComuError("failed to read from conn", err)
}
c.usedAt = time.Now()
return &RawResponsePacket{
resps: resps,
}, nil
}
type BuiltQuery struct {
*QueryPacket
string
}
func (c *Conn) ExecQuery(bq BuiltQuery) (*ResponsePacket, error) {
if bq.ctx != nil {
select {
default:
case <-bq.ctx.Done():
return nil, bq.ctx.Err()
}
}
if err := c.checkClosed(); err != nil {
return nil, err
}
_, err := c.netConn.Write([]byte(bq.string))
if err != nil {
c.errClose(err)
return nil, NewComuError("failed to write to conn", err)
}
resps, err := c.respReader.Read(c.netConn)
if err != nil {
c.errClose(err)
return nil, NewComuError("failed to read from conn", err)
}
for i := 0; i < len(resps); i++ {
if protoErr := bq.actions[i].ValidateProtocol(resps[i].Value); protoErr != nil {
resps[i].Err = protoErr
}
}
c.usedAt = time.Now()
return &ResponsePacket{
query: bq.QueryPacket,
resps: resps,
}, nil
}
func (c *Conn) BuildQuery(p *QueryPacket) (BuiltQuery, error) {
if p.ctx != nil {
select {
default:
case <-p.ctx.Done():
return BuiltQuery{}, p.ctx.Err()
}
}
if err := c.checkClosed(); err != nil {
return BuiltQuery{}, err
}
if p.actions == nil || len(p.actions) == 0 {
return BuiltQuery{p, ""}, NewUsageError("empty packet (0 action)", nil)
}
c.strBuilder.Reset()
if len(p.actions) > 1 { // pipelined
fmt.Fprintf(c.strBuilder, "*%d\n", len(p.actions))
} else {
c.strBuilder.WriteString("*1\n")
}
for _, q := range p.actions {
err := q.AppendToPacket(c.strBuilder)
if err != nil {
return BuiltQuery{}, err
}
}
c.usedAt = time.Now()
return BuiltQuery{p, c.strBuilder.String()}, nil
}
func (c *Conn) BuildAndExecQuery(p *QueryPacket) (*ResponsePacket, error) {
if err := c.checkClosed(); err != nil {
return nil, err
}
bq, err := c.BuildQuery(p)
if err != nil {
return nil, fmt.Errorf("failed building: %w", err)
}
rp, err := c.ExecQuery(bq)
if err != nil {
return nil, fmt.Errorf("failed execution: %w", err)
}
c.usedAt = time.Now()
return rp, nil
}