forked from smallnest/rpcx
/
client.go
756 lines (649 loc) ยท 18.1 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
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
package client
import (
"bufio"
"bytes"
"context"
"crypto/tls"
"errors"
"io"
"net"
"net/url"
"strconv"
"sync"
"time"
opentracing "github.com/opentracing/opentracing-go"
circuit "github.com/rubyist/circuitbreaker"
"github.com/smallnest/rpcx/log"
"github.com/smallnest/rpcx/protocol"
"github.com/smallnest/rpcx/share"
"go.opencensus.io/trace"
)
const (
XVersion = "X-RPCX-Version"
XMessageType = "X-RPCX-MesssageType"
XHeartbeat = "X-RPCX-Heartbeat"
XOneway = "X-RPCX-Oneway"
XMessageStatusType = "X-RPCX-MessageStatusType"
XSerializeType = "X-RPCX-SerializeType"
XMessageID = "X-RPCX-MessageID"
XServicePath = "X-RPCX-ServicePath"
XServiceMethod = "X-RPCX-ServiceMethod"
XMeta = "X-RPCX-Meta"
XErrorMessage = "X-RPCX-ErrorMessage"
)
// ServiceError is an error from server.
type ServiceError string
func (e ServiceError) Error() string {
return string(e)
}
// DefaultOption is a common option configuration for client.
var DefaultOption = Option{
Retries: 3,
RPCPath: share.DefaultRPCPath,
ConnectTimeout: 10 * time.Second,
SerializeType: protocol.MsgPack,
CompressType: protocol.None,
BackupLatency: 10 * time.Millisecond,
}
// Breaker is a CircuitBreaker interface.
type Breaker interface {
Call(func() error, time.Duration) error
Fail()
Success()
Ready() bool
}
// CircuitBreaker is a default circuit breaker (RateBreaker(0.95, 100)).
var CircuitBreaker Breaker = circuit.NewRateBreaker(0.95, 100)
// ErrShutdown connection is closed.
var (
ErrShutdown = errors.New("connection is shut down")
ErrUnsupportedCodec = errors.New("unsupported codec")
)
const (
// ReaderBuffsize is used for bufio reader.
ReaderBuffsize = 16 * 1024
// WriterBuffsize is used for bufio writer.
WriterBuffsize = 16 * 1024
)
type seqKey struct{}
// RPCClient is interface that defines one client to call one server.
type RPCClient interface {
Connect(network, address string) error
Go(ctx context.Context, servicePath, serviceMethod string, args interface{}, reply interface{}, done chan *Call) *Call
Call(ctx context.Context, servicePath, serviceMethod string, args interface{}, reply interface{}) error
SendRaw(ctx context.Context, r *protocol.Message) (map[string]string, []byte, error)
Close() error
RegisterServerMessageChan(ch chan<- *protocol.Message)
UnregisterServerMessageChan()
IsClosing() bool
IsShutdown() bool
}
// Client represents a RPC client.
type Client struct {
option Option
Conn net.Conn
r *bufio.Reader
//w *bufio.Writer
mutex sync.Mutex // protects following
seq uint64
pending map[uint64]*Call
closing bool // user has called Close
shutdown bool // server has told us to stop
pluginClosed bool // the plugin has been called
Plugins PluginContainer
ServerMessageChan chan<- *protocol.Message
}
// NewClient returns a new Client with the option.
func NewClient(option Option) *Client {
return &Client{
option: option,
}
}
// Option contains all options for creating clients.
type Option struct {
// Group is used to select the services in the same group. Services set group info in their meta.
// If it is empty, clients will ignore group.
Group string
// Retries retries to send
Retries int
// TLSConfig for tcp and quic
TLSConfig *tls.Config
// kcp.BlockCrypt
Block interface{}
// RPCPath for http connection
RPCPath string
//ConnectTimeout sets timeout for dialing
ConnectTimeout time.Duration
// ReadTimeout sets readdeadline for underlying net.Conns
ReadTimeout time.Duration
// WriteTimeout sets writedeadline for underlying net.Conns
WriteTimeout time.Duration
// BackupLatency is used for Failbackup mode. rpcx will sends another request if the first response doesn't return in BackupLatency time.
BackupLatency time.Duration
// Breaker is used to config CircuitBreaker
GenBreaker func() Breaker
SerializeType protocol.SerializeType
CompressType protocol.CompressType
Heartbeat bool
HeartbeatInterval time.Duration
}
// Call represents an active RPC.
type Call struct {
ServicePath string // The name of the service and method to call.
ServiceMethod string // The name of the service and method to call.
Metadata map[string]string //metadata
ResMetadata map[string]string
Args interface{} // The argument to the function (*struct).
Reply interface{} // The reply from the function (*struct).
Error error // After completion, the error status.
Done chan *Call // Strobes when call is complete.
Raw bool // raw message or not
}
func (call *Call) done() {
select {
case call.Done <- call:
// ok
default:
log.Debug("rpc: discarding Call reply due to insufficient Done chan capacity")
}
}
// RegisterServerMessageChan registers the channel that receives server requests.
func (client *Client) RegisterServerMessageChan(ch chan<- *protocol.Message) {
client.ServerMessageChan = ch
}
// UnregisterServerMessageChan removes ServerMessageChan.
func (client *Client) UnregisterServerMessageChan() {
client.ServerMessageChan = nil
}
// IsClosing client is closing or not.
func (client *Client) IsClosing() bool {
client.mutex.Lock()
defer client.mutex.Unlock()
return client.closing
}
// IsShutdown client is shutdown or not.
func (client *Client) IsShutdown() bool {
client.mutex.Lock()
defer client.mutex.Unlock()
return client.shutdown
}
// Go invokes the function asynchronously. It returns the Call structure representing
// the invocation. The done channel will signal when the call is complete by returning
// the same Call object. If done is nil, Go will allocate a new channel.
// If non-nil, done must be buffered or Go will deliberately crash.
func (client *Client) Go(ctx context.Context, servicePath, serviceMethod string, args interface{}, reply interface{}, done chan *Call) *Call {
call := new(Call)
call.ServicePath = servicePath
call.ServiceMethod = serviceMethod
meta := ctx.Value(share.ReqMetaDataKey)
if meta != nil { //copy meta in context to meta in requests
call.Metadata = meta.(map[string]string)
}
if _, ok := ctx.(*share.Context); !ok {
ctx = share.NewContext(ctx)
}
// TODO: should implement as plugin
client.injectOpenTracingSpan(ctx, call)
client.injectOpenCensusSpan(ctx, call)
call.Args = args
call.Reply = reply
if done == nil {
done = make(chan *Call, 10) // buffered.
} else {
// If caller passes done != nil, it must arrange that
// done has enough buffer for the number of simultaneous
// RPCs that will be using that channel. If the channel
// is totally unbuffered, it's best not to run at all.
if cap(done) == 0 {
log.Panic("rpc: done channel is unbuffered")
}
}
call.Done = done
client.send(ctx, call)
return call
}
func (client *Client) injectOpenTracingSpan(ctx context.Context, call *Call) {
var rpcxContext *share.Context
var ok bool
if rpcxContext, ok = ctx.(*share.Context); !ok {
return
}
sp := rpcxContext.Value(share.OpentracingSpanClientKey)
if sp == nil { // have not config opentracing plugin
return
}
span := sp.(opentracing.Span)
if call.Metadata == nil {
call.Metadata = make(map[string]string)
}
meta := call.Metadata
err := opentracing.GlobalTracer().Inject(
span.Context(),
opentracing.TextMap,
opentracing.TextMapCarrier(meta))
if err != nil {
log.Errorf("failed to inject span: %v", err)
}
}
func (client *Client) injectOpenCensusSpan(ctx context.Context, call *Call) {
var rpcxContext *share.Context
var ok bool
if rpcxContext, ok = ctx.(*share.Context); !ok {
return
}
sp := rpcxContext.Value(share.OpencensusSpanClientKey)
if sp == nil { // have not config opencensus plugin
return
}
span := sp.(*trace.Span)
if span == nil {
return
}
if call.Metadata == nil {
call.Metadata = make(map[string]string)
}
meta := call.Metadata
spanContext := span.SpanContext()
scData := make([]byte, 24)
copy(scData[:16], spanContext.TraceID[:])
copy(scData[16:24], spanContext.SpanID[:])
meta[share.OpencensusSpanRequestKey] = string(scData)
}
// Call invokes the named function, waits for it to complete, and returns its error status.
func (client *Client) Call(ctx context.Context, servicePath, serviceMethod string, args interface{}, reply interface{}) error {
return client.call(ctx, servicePath, serviceMethod, args, reply)
}
func (client *Client) call(ctx context.Context, servicePath, serviceMethod string, args interface{}, reply interface{}) error {
seq := new(uint64)
ctx = context.WithValue(ctx, seqKey{}, seq)
Done := client.Go(ctx, servicePath, serviceMethod, args, reply, make(chan *Call, 1)).Done
var err error
select {
case <-ctx.Done(): //cancel by context
client.mutex.Lock()
call := client.pending[*seq]
delete(client.pending, *seq)
client.mutex.Unlock()
if call != nil {
call.Error = ctx.Err()
call.done()
}
return ctx.Err()
case call := <-Done:
err = call.Error
meta := ctx.Value(share.ResMetaDataKey)
if meta != nil && len(call.ResMetadata) > 0 {
resMeta := meta.(map[string]string)
for k, v := range call.ResMetadata {
resMeta[k] = v
}
}
}
return err
}
// SendRaw sends raw messages. You don't care args and replys.
func (client *Client) SendRaw(ctx context.Context, r *protocol.Message) (map[string]string, []byte, error) {
ctx = context.WithValue(ctx, seqKey{}, r.Seq())
call := new(Call)
call.Raw = true
call.ServicePath = r.ServicePath
call.ServiceMethod = r.ServiceMethod
meta := ctx.Value(share.ReqMetaDataKey)
rmeta := make(map[string]string)
// copy meta to rmeta
if meta != nil {
for k, v := range meta.(map[string]string) {
rmeta[k] = v
}
}
// copy r.Metadata to rmeta
if r.Metadata != nil {
for k, v := range r.Metadata {
rmeta[k] = v
}
}
if meta != nil { //copy meta in context to meta in requests
call.Metadata = rmeta
}
r.Metadata = rmeta
done := make(chan *Call, 10)
call.Done = done
seq := r.Seq()
client.mutex.Lock()
if client.pending == nil {
client.pending = make(map[uint64]*Call)
}
client.pending[seq] = call
client.mutex.Unlock()
data := r.EncodeSlicePointer()
_, err := client.Conn.Write(*data)
protocol.PutData(data)
if err != nil {
client.mutex.Lock()
call = client.pending[seq]
delete(client.pending, seq)
client.mutex.Unlock()
if call != nil {
call.Error = err
call.done()
}
return nil, nil, err
}
if r.IsOneway() {
client.mutex.Lock()
call = client.pending[seq]
delete(client.pending, seq)
client.mutex.Unlock()
if call != nil {
call.done()
}
return nil, nil, nil
}
var m map[string]string
var payload []byte
select {
case <-ctx.Done(): //cancel by context
client.mutex.Lock()
call := client.pending[seq]
delete(client.pending, seq)
client.mutex.Unlock()
if call != nil {
call.Error = ctx.Err()
call.done()
}
return nil, nil, ctx.Err()
case call := <-done:
err = call.Error
m = call.Metadata
if call.Reply != nil {
payload = call.Reply.([]byte)
}
}
return m, payload, err
}
func convertRes2Raw(res *protocol.Message) (map[string]string, []byte, error) {
m := make(map[string]string)
m[XVersion] = strconv.Itoa(int(res.Version()))
if res.IsHeartbeat() {
m[XHeartbeat] = "true"
}
if res.IsOneway() {
m[XOneway] = "true"
}
if res.MessageStatusType() == protocol.Error {
m[XMessageStatusType] = "Error"
} else {
m[XMessageStatusType] = "Normal"
}
if res.CompressType() == protocol.Gzip {
m["Content-Encoding"] = "gzip"
}
m[XMeta] = urlencode(res.Metadata)
m[XSerializeType] = strconv.Itoa(int(res.SerializeType()))
m[XMessageID] = strconv.FormatUint(res.Seq(), 10)
m[XServicePath] = res.ServicePath
m[XServiceMethod] = res.ServiceMethod
return m, res.Payload, nil
}
func urlencode(data map[string]string) string {
if len(data) == 0 {
return ""
}
var buf bytes.Buffer
for k, v := range data {
buf.WriteString(url.QueryEscape(k))
buf.WriteByte('=')
buf.WriteString(url.QueryEscape(v))
buf.WriteByte('&')
}
s := buf.String()
return s[0 : len(s)-1]
}
func (client *Client) send(ctx context.Context, call *Call) {
// Register this call.
client.mutex.Lock()
if client.shutdown || client.closing {
call.Error = ErrShutdown
client.mutex.Unlock()
call.done()
return
}
codec := share.Codecs[client.option.SerializeType]
if codec == nil {
call.Error = ErrUnsupportedCodec
client.mutex.Unlock()
call.done()
return
}
if client.pending == nil {
client.pending = make(map[uint64]*Call)
}
seq := client.seq
client.seq++
client.pending[seq] = call
client.mutex.Unlock()
if cseq, ok := ctx.Value(seqKey{}).(*uint64); ok {
*cseq = seq
}
//req := protocol.NewMessage()
req := protocol.GetPooledMsg()
req.SetMessageType(protocol.Request)
req.SetSeq(seq)
if call.Reply == nil {
req.SetOneway(true)
}
// heartbeat
if call.ServicePath == "" && call.ServiceMethod == "" {
req.SetHeartbeat(true)
} else {
req.SetSerializeType(client.option.SerializeType)
if call.Metadata != nil {
req.Metadata = call.Metadata
}
req.ServicePath = call.ServicePath
req.ServiceMethod = call.ServiceMethod
data, err := codec.Encode(call.Args)
if err != nil {
delete(client.pending, seq)
call.Error = err
call.done()
return
}
if len(data) > 1024 && client.option.CompressType != protocol.None {
req.SetCompressType(client.option.CompressType)
}
req.Payload = data
}
if client.Plugins != nil {
client.Plugins.DoClientBeforeEncode(req)
}
data := req.EncodeSlicePointer()
_, err := client.Conn.Write(*data)
protocol.PutData(data)
if err != nil {
client.mutex.Lock()
call = client.pending[seq]
delete(client.pending, seq)
client.mutex.Unlock()
if call != nil {
call.Error = err
call.done()
}
protocol.FreeMsg(req)
return
}
isOneway := req.IsOneway()
protocol.FreeMsg(req)
if isOneway {
client.mutex.Lock()
call = client.pending[seq]
delete(client.pending, seq)
client.mutex.Unlock()
if call != nil {
call.done()
}
}
if client.option.WriteTimeout != 0 {
client.Conn.SetWriteDeadline(time.Now().Add(client.option.WriteTimeout))
}
}
func (client *Client) input() {
var err error
for err == nil {
var res = protocol.NewMessage()
if client.option.ReadTimeout != 0 {
client.Conn.SetReadDeadline(time.Now().Add(client.option.ReadTimeout))
}
err = res.Decode(client.r)
if err != nil {
break
}
if client.Plugins != nil {
client.Plugins.DoClientAfterDecode(res)
}
seq := res.Seq()
var call *Call
isServerMessage := (res.MessageType() == protocol.Request && !res.IsHeartbeat() && res.IsOneway())
if !isServerMessage {
client.mutex.Lock()
call = client.pending[seq]
delete(client.pending, seq)
client.mutex.Unlock()
}
switch {
case call == nil:
if isServerMessage {
if client.ServerMessageChan != nil {
go client.handleServerRequest(res)
}
continue
}
case res.MessageStatusType() == protocol.Error:
// We've got an error response. Give this to the request
if len(res.Metadata) > 0 {
call.ResMetadata = res.Metadata
call.Error = ServiceError(res.Metadata[protocol.ServiceError])
}
if call.Raw {
call.Metadata, call.Reply, _ = convertRes2Raw(res)
call.Metadata[XErrorMessage] = call.Error.Error()
}
call.done()
default:
if call.Raw {
call.Metadata, call.Reply, _ = convertRes2Raw(res)
} else {
data := res.Payload
if len(data) > 0 {
codec := share.Codecs[res.SerializeType()]
if codec == nil {
call.Error = ServiceError(ErrUnsupportedCodec.Error())
} else {
err = codec.Decode(data, call.Reply)
if err != nil {
call.Error = ServiceError(err.Error())
}
}
}
if len(res.Metadata) > 0 {
call.ResMetadata = res.Metadata
}
}
call.done()
}
}
// Terminate pending calls.
if client.ServerMessageChan != nil {
req := protocol.NewMessage()
req.SetMessageType(protocol.Request)
req.SetMessageStatusType(protocol.Error)
if req.Metadata == nil {
req.Metadata = make(map[string]string)
if err != nil {
req.Metadata[protocol.ServiceError] = err.Error()
}
}
req.Metadata["server"] = client.Conn.RemoteAddr().String()
go client.handleServerRequest(req)
}
client.mutex.Lock()
if !client.pluginClosed {
if client.Plugins != nil {
client.Plugins.DoClientConnectionClose(client.Conn)
}
client.pluginClosed = true
}
client.Conn.Close()
client.shutdown = true
closing := client.closing
if err == io.EOF {
if closing {
err = ErrShutdown
} else {
err = io.ErrUnexpectedEOF
}
}
for _, call := range client.pending {
call.Error = err
call.done()
}
client.mutex.Unlock()
if err != nil && err != io.EOF && !closing {
log.Error("rpcx: client protocol error:", err)
}
}
func (client *Client) handleServerRequest(msg *protocol.Message) {
defer func() {
if r := recover(); r != nil {
log.Errorf("ServerMessageChan may be closed so client remove it. Please add it again if you want to handle server requests. error is %v", r)
client.ServerMessageChan = nil
}
}()
t := time.NewTimer(5 * time.Second)
select {
case client.ServerMessageChan <- msg:
case <-t.C:
log.Warnf("ServerMessageChan may be full so the server request %d has been dropped", msg.Seq())
}
t.Stop()
}
func (client *Client) heartbeat() {
t := time.NewTicker(client.option.HeartbeatInterval)
for range t.C {
if client.IsShutdown() || client.IsClosing() {
t.Stop()
return
}
err := client.Call(context.Background(), "", "", nil, nil)
if err != nil {
log.Warnf("failed to heartbeat to %s", client.Conn.RemoteAddr().String())
}
}
}
// Close calls the underlying connection's Close method. If the connection is already
// shutting down, ErrShutdown is returned.
func (client *Client) Close() error {
client.mutex.Lock()
for seq, call := range client.pending {
delete(client.pending, seq)
if call != nil {
call.Error = ErrShutdown
call.done()
}
}
var err error
if !client.pluginClosed {
if client.Plugins != nil {
client.Plugins.DoClientConnectionClose(client.Conn)
}
client.pluginClosed = true
err = client.Conn.Close()
}
if client.closing || client.shutdown {
client.mutex.Unlock()
return ErrShutdown
}
client.closing = true
client.mutex.Unlock()
return err
}