This repository has been archived by the owner on Jun 5, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
client.go
640 lines (510 loc) · 13 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
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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
package bus
import (
"context"
"encoding/binary"
"errors"
"fmt"
"sync"
"time"
"github.com/golang/protobuf/proto"
"go.uber.org/atomic"
"go.ytsaurus.tech/library/go/core/log"
"go.ytsaurus.tech/library/go/core/log/nop"
"go.ytsaurus.tech/library/go/core/xerrors"
"go.ytsaurus.tech/library/go/ptr"
"github.com/go-faster/yt/compression"
"github.com/go-faster/yt/guid"
"github.com/go-faster/yt/proto/core/misc"
"github.com/go-faster/yt/proto/core/rpc"
"github.com/go-faster/yt/yterrors"
)
const (
// defaultAcknowledgementTimeout is a default timeout used to cancel inflight unacked requests.
defaultAcknowledgementTimeout = time.Second * 5
// effectiveTimeout is a request timeout used when user has
// neither set context deadline nor specified request timeout.
effectiveTimeout = time.Hour * 24
)
// featureIDFormatter is a function that converts feature id to string.
type featureIDFormatter func(i int32) string
// defaultFeatureIDFormatter simply converts number to string.
func defaultFeatureIDFormatter(i int32) string {
return fmt.Sprintf("%d", i)
}
type clientReq struct {
id guid.GUID
reqHeader *rpc.TRequestHeader
rspHeader *rpc.TResponseHeader
request, reply proto.Message
reqAttachments [][]byte
rspAttachments [][]byte
acknowledgementTimeout *time.Duration
acked atomic.Bool
done chan error
}
type msgType uint32
const (
maxInFlightRequests = 1000
msgRequest msgType = 0x69637072
msgCancel msgType = 0x63637072
msgResponse msgType = 0x6f637072
msgStreamPayload msgType = 0x70637072
msgStreamFeedback msgType = 0x66637072
)
var (
ytGoClient = "YT go client"
codecNone int32 = 0
)
type ClientOption func(conn *ClientConn)
func WithLogger(l log.Logger) ClientOption {
return func(conn *ClientConn) {
conn.log = l
}
}
func WithDefaultProtocolVersionMajor(v int32) ClientOption {
return func(conn *ClientConn) {
conn.defaultProtocolVersionMajor = v
}
}
func WithFeatureIDFormatter(f featureIDFormatter) ClientOption {
return func(conn *ClientConn) {
conn.featureIDFormatter = f
}
}
var ErrConnClosed = xerrors.NewSentinel("connection closed")
type ClientConn struct {
l sync.Mutex
err error
stop chan struct{}
reqs map[guid.GUID]*clientReq
sendQueue, cancelQueue chan *clientReq
// mu guards the following maps.
mu sync.Mutex
// unackedReqs stores unacked request id to packet id mapping.
unackedReqs map[guid.GUID]guid.GUID
// unackedPackets stores unacked packet id to request id mapping.
unackedPackets map[guid.GUID]guid.GUID
defaultProtocolVersionMajor int32
featureIDFormatter featureIDFormatter
address string
dialed chan struct{}
bus *Bus
log log.Logger
}
func NewClient(ctx context.Context, address string, opts ...ClientOption) *ClientConn {
l := &nop.Logger{}
client := &ClientConn{
reqs: make(map[guid.GUID]*clientReq, maxInFlightRequests),
sendQueue: make(chan *clientReq, maxInFlightRequests),
cancelQueue: make(chan *clientReq, maxInFlightRequests),
stop: make(chan struct{}),
featureIDFormatter: defaultFeatureIDFormatter,
unackedReqs: make(map[guid.GUID]guid.GUID),
unackedPackets: make(map[guid.GUID]guid.GUID),
address: address,
dialed: make(chan struct{}),
log: l,
}
for _, opt := range opts {
opt(client)
}
go client.dial(ctx)
go client.runSender()
go client.runReceiver()
return client
}
func (c *ClientConn) Close() {
c.l.Lock()
defer c.l.Unlock()
if c.bus != nil {
c.bus.Close()
}
if c.err == nil {
c.err = ErrConnClosed
close(c.stop)
}
}
func (c *ClientConn) Done() <-chan struct{} {
return c.stop
}
func (c *ClientConn) Err() (err error) {
c.l.Lock()
err = c.err
c.l.Unlock()
return
}
func (c *ClientConn) fail(err error) {
c.l.Lock()
if c.err == nil {
c.err = ErrConnClosed.Wrap(err)
close(c.stop)
}
c.l.Unlock()
}
func (c *ClientConn) runSender() {
select {
case <-c.dialed:
case <-c.stop:
return
}
for {
select {
case req := <-c.cancelQueue:
c.l.Lock()
delete(c.reqs, req.id)
c.l.Unlock()
c.deleteUnackedReq(req.id)
cancelReq := &clientReq{
id: guid.New(),
reqHeader: &rpc.TRequestHeader{
RequestId: req.reqHeader.RequestId,
Service: req.reqHeader.Service,
Method: req.reqHeader.Method,
RealmId: req.reqHeader.RealmId,
UserAgent: &ytGoClient,
RequestCodec: &codecNone,
ResponseCodec: &codecNone,
},
request: &rpc.TRequestCancelationHeader{
RequestId: req.reqHeader.RequestId,
Service: req.reqHeader.Service,
Method: req.reqHeader.Method,
RealmId: req.reqHeader.RealmId,
},
}
msg, err := c.buildMsg(cancelReq, msgCancel)
if err != nil {
c.fail(err)
return
}
packetID := guid.New()
c.log.Debug("Sending cancel packet",
log.String("id", packetID.String()),
log.String("request_id", misc.NewGUIDFromProto(req.reqHeader.RequestId).String()))
if err := c.bus.Send(packetID, msg, &busSendOptions{}); err != nil {
c.fail(err)
return
}
case req := <-c.sendQueue:
msg, err := c.buildMsg(req, msgRequest)
if err != nil {
req.done <- err
continue
}
c.l.Lock()
c.reqs[req.id] = req
c.l.Unlock()
opts := &busSendOptions{}
if req.acknowledgementTimeout != nil {
opts.DeliveryTrackingLevel = DeliveryTrackingLevelFull
}
packetID := guid.New()
if req.acknowledgementTimeout != nil {
c.addUnackedReq(req.id, packetID)
}
c.log.Debug("Sending packet",
log.String("id", packetID.String()),
log.String("request_id", misc.NewGUIDFromProto(req.reqHeader.RequestId).String()))
if err := c.bus.Send(packetID, msg, opts); err != nil {
c.fail(err)
return
}
case <-c.stop:
return
}
}
}
func (c *ClientConn) dial(ctx context.Context) {
bus, err := Dial(ctx, Options{Address: c.address, Logger: c.log})
if err != nil {
c.fail(err)
return
}
c.l.Lock()
if c.err != nil {
bus.Close()
} else {
c.bus = bus
}
c.l.Unlock()
close(c.dialed)
}
func (c *ClientConn) buildMsg(req *clientReq, msgType msgType) ([][]byte, error) {
msg := make([][]byte, 2+len(req.reqAttachments))
var err error
var protoHeader []byte
if protoHeader, err = proto.Marshal(req.reqHeader); err != nil {
return nil, err
}
msg[0] = make([]byte, 4, 4+len(protoHeader))
binary.LittleEndian.PutUint32(msg[0], uint32(msgType))
msg[0] = append(msg[0], protoHeader...)
data, err := proto.Marshal(req.request)
if err != nil {
return nil, err
}
codecID := compression.CodecIDNone
if req.reqHeader.RequestCodec != nil {
codecID = compression.CodecID(*req.reqHeader.RequestCodec)
}
codec := compression.NewCodec(codecID)
compressed, err := codec.Compress(data)
if err != nil {
return nil, err
}
msg[1] = compressed
for i, a := range req.reqAttachments {
compressed, err := codec.Compress(a)
if err != nil {
return nil, err
}
msg[2+i] = compressed
}
return msg, nil
}
func (c *ClientConn) handleAck(packetID guid.GUID) {
reqID, ok := c.deleteUnackedPacket(packetID)
if !ok {
return
}
c.l.Lock()
req, ok := c.reqs[reqID]
c.l.Unlock()
if !ok {
return
}
req.acked.Store(true)
}
func (c *ClientConn) handleMsg(msg [][]byte) error {
if len(msg) == 0 {
return fmt.Errorf("bus: received empty message")
}
if len(msg[0]) < 4 {
return fmt.Errorf("bus: message type is missing")
}
if typ := msgType(binary.LittleEndian.Uint32(msg[0][:4])); typ != msgResponse {
c.log.Warnf("ignoring message of unexpected type: got %x, want %x", typ, msgResponse)
return nil
}
var rsp rpc.TResponseHeader
if err := proto.Unmarshal(msg[0][4:], &rsp); err != nil {
return err
}
if rsp.RequestId == nil {
return fmt.Errorf("bus: response is missing request_id")
}
reqID := misc.NewGUIDFromProto(rsp.RequestId)
c.l.Lock()
req, ok := c.reqs[reqID]
delete(c.reqs, reqID)
c.l.Unlock()
if !ok {
c.log.Warn("request not found; ignoring", log.String("request_id", reqID.String()))
return nil
}
req.rspHeader = &rsp
if replyErr := misc.NewErrorFromProto(req.rspHeader.Error); replyErr != nil {
req.done <- replyErr
return nil
}
if len(msg) < 2 {
req.done <- fmt.Errorf("bus: reply body is missing")
return nil
}
codecID := compression.CodecIDNone
if req.reqHeader.ResponseCodec != nil {
codecID = compression.CodecID(*req.reqHeader.ResponseCodec)
}
codec := compression.NewCodec(codecID)
reply, err := codec.Decompress(msg[1])
if err != nil {
req.done <- err
return nil
}
if err := proto.Unmarshal(reply, req.reply); err != nil {
req.done <- err
return nil
}
for _, a := range msg[2:] {
decompressed, err := codec.Decompress(a)
if err != nil {
req.done <- err
return nil
}
req.rspAttachments = append(req.rspAttachments, decompressed)
}
req.done <- nil
return nil
}
func (c *ClientConn) runReceiver() {
select {
case <-c.dialed:
case <-c.stop:
return
}
for {
msg, err := c.bus.Receive()
if err != nil {
c.fail(err)
return
}
switch msg.fixHeader.typ {
case packetAck:
c.handleAck(msg.fixHeader.packetID)
default:
if err := c.handleMsg(msg.parts); err != nil {
c.fail(err)
return
}
}
}
}
func (c *ClientConn) Send(
ctx context.Context,
service, method string,
request, reply proto.Message,
opts ...SendOption,
) error {
reqID := guid.New()
req := &clientReq{
id: reqID,
request: request,
reply: reply,
reqHeader: &rpc.TRequestHeader{
RequestId: misc.NewProtoFromGUID(reqID),
Service: &service,
Method: &method,
ProtocolVersionMajor: &c.defaultProtocolVersionMajor,
UserAgent: &ytGoClient,
RequestCodec: &codecNone,
ResponseCodec: &codecNone,
},
acknowledgementTimeout: ptr.Duration(defaultAcknowledgementTimeout),
done: make(chan error, 1),
}
for _, opt := range opts {
opt.before(req)
}
userDeadline, hasUserDeadline := ctx.Deadline()
if hasUserDeadline && req.reqHeader.Timeout == nil {
if timeout := time.Until(userDeadline); timeout > 0 {
req.reqHeader.Timeout = ptr.Int64(durationToMicroseconds(timeout))
}
}
select {
case c.sendQueue <- req:
case <-c.stop:
return c.err
case <-ctx.Done():
return ctx.Err()
}
reqCtx := ctx
if !hasUserDeadline {
effectiveTimeout := effectiveTimeout
if req.reqHeader.Timeout != nil {
effectiveTimeout = microsecondsToDuration(*req.reqHeader.Timeout)
}
var cancel func()
reqCtx, cancel = context.WithTimeout(ctx, effectiveTimeout)
defer cancel()
}
var ackTimeout <-chan time.Time
if req.acknowledgementTimeout != nil {
t := time.NewTimer(*req.acknowledgementTimeout)
defer func() { _ = t.Stop() }()
ackTimeout = t.C
}
loop:
select {
case <-c.stop:
return c.err
case err := <-req.done:
if err != nil {
c.enrichClientRequestErrorWithFeatureName(err)
return err
}
case <-ackTimeout:
if req.acked.Load() {
goto loop
}
c.finishReq(req)
err := yterrors.Err(yterrors.CodeTimeout, "Request acknowledgement timed out")
c.log.Error("Request acknowledgement timeout", log.Error(err))
return err
case <-reqCtx.Done():
c.finishReq(req)
if errors.Is(reqCtx.Err(), context.DeadlineExceeded) {
msg := "Request timed out or timer was aborted"
if ctx.Err() == nil {
msg = "Request timed out"
}
err := yterrors.Err(yterrors.CodeTimeout, msg)
c.log.Error("Request timeout", log.Error(err))
return err
} else if errors.Is(reqCtx.Err(), context.Canceled) {
err := yterrors.Err(yterrors.CodeCanceled, "Request canceled")
c.log.Error("Context canceled", log.Error(err))
return err
}
return ctx.Err()
}
for _, opt := range opts {
opt.after(req)
}
return nil
}
func (c *ClientConn) finishReq(req *clientReq) {
select {
case c.cancelQueue <- req:
default:
c.l.Lock()
delete(c.reqs, req.id)
c.l.Unlock()
c.deleteUnackedReq(req.id)
}
}
func (c *ClientConn) enrichClientRequestErrorWithFeatureName(err error) {
yterr, ok := err.(*yterrors.Error)
if !ok {
return
}
if yterr.Code != yterrors.CodeUnsupportedServerFeature ||
!yterr.HasAttr(string(AttributeKeyFeatureID)) ||
yterr.HasAttr(string(AttributeKeyFeatureName)) {
return
}
featureID := int32(yterr.Attributes[string(AttributeKeyFeatureID)].(int64))
yterr.AddAttr(string(AttributeKeyFeatureName), c.featureIDFormatter(featureID))
}
func (c *ClientConn) addUnackedReq(reqID, packetID guid.GUID) {
c.mu.Lock()
defer c.mu.Unlock()
c.unackedReqs[reqID] = packetID
c.unackedPackets[packetID] = reqID
}
func (c *ClientConn) deleteUnackedReq(reqID guid.GUID) {
c.mu.Lock()
defer c.mu.Unlock()
packetID, ok := c.unackedReqs[reqID]
if ok {
delete(c.unackedPackets, packetID)
}
delete(c.unackedReqs, reqID)
}
func (c *ClientConn) deleteUnackedPacket(packetID guid.GUID) (guid.GUID, bool) {
c.mu.Lock()
defer c.mu.Unlock()
reqID, ok := c.unackedPackets[packetID]
if !ok {
return guid.GUID{}, false
}
delete(c.unackedPackets, packetID)
delete(c.unackedReqs, reqID)
return reqID, true
}
func durationToMicroseconds(d time.Duration) int64 {
return int64(d / time.Microsecond)
}
func microsecondsToDuration(us int64) time.Duration {
return time.Microsecond * time.Duration(us)
}