forked from valyala/gorpc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
717 lines (625 loc) · 18.3 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
package gorpc
import (
"fmt"
"io"
"sync"
"time"
)
// Client implements RPC client.
//
// The client must be started with Client.Start() before use.
//
// It is absolutely safe and encouraged using a single client across arbitrary
// number of concurrently running goroutines.
//
// Default client settings are optimized for high load, so don't override
// them without valid reason.
type Client struct {
// Server address to connect to.
//
// The address format depends on the underlying transport provided
// by Client.Dial. The following transports are provided out of the box:
// * TCP - see NewTCPClient() and NewTCPServer().
// * TLS - see NewTLSClient() and NewTLSServer().
// * Unix sockets - see NewUnixClient() and NewUnixServer().
//
// By default TCP transport is used.
Addr string
// The number of concurrent connections the client should establish
// to the sever.
// By default only one connection is established.
Conns int
// The maximum number of pending requests in the queue.
//
// The number of pending requsts should exceed the expected number
// of concurrent goroutines calling client's methods.
// Otherwise a lot of ClientError.Overflow errors may appear.
//
// Default is DefaultPendingMessages.
PendingRequests int
// Delay between request flushes.
//
// Negative values lead to immediate requests' sending to the server
// without their buffering. This minimizes rpc latency at the cost
// of higher CPU and network usage.
//
// Default value is DefaultFlushDelay.
FlushDelay time.Duration
// Maximum request time.
// Default value is DefaultRequestTimeout.
RequestTimeout time.Duration
// Disable data compression.
// By default data compression is enabled.
DisableCompression bool
// Size of send buffer per each underlying connection in bytes.
// Default value is DefaultBufferSize.
SendBufferSize int
// Size of recv buffer per each underlying connection in bytes.
// Default value is DefaultBufferSize.
RecvBufferSize int
// OnConnect is called whenever connection to server is established.
// The callback can be used for authentication/authorization/encryption
// and/or for custom transport wrapping.
//
// See also Dial callback, which can be used for sophisticated
// transport implementation.
OnConnect OnConnectFunc
// The client calls this callback when it needs new connection
// to the server.
// The client passes Client.Addr into Dial().
//
// Override this callback if you want custom underlying transport
// and/or authentication/authorization.
// Don't forget overriding Server.Listener accordingly.
//
// See also OnConnect for authentication/authorization purposes.
//
// * NewTLSClient() and NewTLSServer() can be used for encrypted rpc.
// * NewUnixClient() and NewUnixServer() can be used for fast local
// inter-process rpc.
//
// By default it returns TCP connections established to the Client.Addr.
Dial DialFunc
// LogError is used for error logging.
//
// By default the function set via SetErrorLogger() is used.
LogError LoggerFunc
// Connection statistics.
//
// The stats doesn't reset automatically. Feel free resetting it
// any time you wish.
Stats ConnStats
requestsChan chan *AsyncResult
clientStopChan chan struct{}
stopWg sync.WaitGroup
}
// Start starts rpc client. Establishes connection to the server on Client.Addr.
//
// All the response types the server may return must be registered
// via gorpc.RegisterType() before starting the client.
// There is no need in registering base Go types such as int, string, bool,
// float64, etc. or arrays, slices and maps containing base Go types.
func (c *Client) Start() {
if c.LogError == nil {
c.LogError = errorLogger
}
if c.clientStopChan != nil {
panic("gorpc.Client: the given client is already started. Call Client.Stop() before calling Client.Start() again!")
}
if c.PendingRequests <= 0 {
c.PendingRequests = DefaultPendingMessages
}
if c.FlushDelay == 0 {
c.FlushDelay = DefaultFlushDelay
}
if c.RequestTimeout <= 0 {
c.RequestTimeout = DefaultRequestTimeout
}
if c.SendBufferSize <= 0 {
c.SendBufferSize = DefaultBufferSize
}
if c.RecvBufferSize <= 0 {
c.RecvBufferSize = DefaultBufferSize
}
c.requestsChan = make(chan *AsyncResult, c.PendingRequests)
c.clientStopChan = make(chan struct{})
if c.Conns <= 0 {
c.Conns = 1
}
if c.Dial == nil {
c.Dial = defaultDial
}
for i := 0; i < c.Conns; i++ {
c.stopWg.Add(1)
go clientHandler(c)
}
}
// Stop stops rpc client. Stopped client can be started again.
func (c *Client) Stop() {
if c.clientStopChan == nil {
panic("gorpc.Client: the client must be started before stopping it")
}
close(c.clientStopChan)
c.stopWg.Wait()
c.clientStopChan = nil
}
// Call sends the given request to the server and obtains response
// from the server.
// Returns non-nil error if the response cannot be obtained during
// Client.RequestTimeout or server connection problems occur.
// The returned error can be casted to ClientError.
//
// Request and response types may be arbitrary. All the response types
// the server may return must be registered via gorpc.RegisterType() before
// starting the client.
// There is no need in registering base Go types such as int, string, bool,
// float64, etc. or arrays, slices and maps containing base Go types.
//
// Hint: use Dispatcher for distinct calls' construction.
//
// Don't forget starting the client with Client.Start() before calling Client.Call().
func (c *Client) Call(request interface{}) (response interface{}, err error) {
return c.CallTimeout(request, c.RequestTimeout)
}
// CallTimeout sends the given request to the server and obtains response
// from the server.
// Returns non-nil error if the response cannot be obtained during
// the given timeout or server connection problems occur.
// The returned error can be casted to ClientError.
//
// Request and response types may be arbitrary. All the response types
// the server may return must be registered via gorpc.RegisterType() before
// starting the client.
// There is no need in registering base Go types such as int, string, bool,
// float64, etc. or arrays, slices and maps containing base Go types.
//
// Hint: use Dispatcher for distinct calls' construction.
//
// Don't forget starting the client with Client.Start() before calling Client.Call().
func (c *Client) CallTimeout(request interface{}, timeout time.Duration) (response interface{}, err error) {
var m *AsyncResult
if m, err = c.CallAsync(request); err != nil {
return nil, err
}
t := acquireTimer(timeout)
select {
case <-m.Done:
response, err = m.Response, m.Error
case <-t.C:
err = getClientTimeoutError(c, timeout)
}
releaseTimer(t)
return
}
func getClientTimeoutError(c *Client, timeout time.Duration) error {
err := fmt.Errorf("gorpc.Client: [%s]. Cannot obtain response during timeout=%s", c.Addr, timeout)
c.LogError("%s", err)
return &ClientError{
Timeout: true,
err: err,
}
}
// Send sends the given request to the server and doesn't wait for response.
//
// Since this is 'fire and forget' function, which never waits for response,
// it cannot guarantee that the server receives and successfully processes
// the given request. Though in most cases under normal conditions requests
// should reach the server and it should successfully process them.
// Send semantics is similar to UDP messages' semantics.
//
// The server may return arbitrary response on Send() request, but the response
// is totally ignored.
//
// Don't forget starting the client with Client.Start() before calling Client.Send().
func (c *Client) Send(request interface{}) error {
_, err := c.callAsync(request, true)
return err
}
// AsyncResult is a result returned from Client.CallAsync().
type AsyncResult struct {
// The response can be read only after <-Done unblocks.
Response interface{}
// The error can be read only after <-Done unblocks.
// The error can be casted to ClientError.
Error error
// Response and Error become available after <-Done unblocks.
Done <-chan struct{}
request interface{}
t time.Time
done chan struct{}
}
// CallAsync starts async rpc call.
//
// Rpc call is complete after <-AsyncResult.Done unblocks.
// If you want canceling the request, just throw away the returned AsyncResult.
//
// CallAsync doesn't respect Client.RequestTimeout - response timeout
// may be controlled by the caller via something like:
//
// r := c.CallAsync("foobar")
// select {
// case <-time.After(c.RequestTimeout):
// log.Printf("rpc timeout!")
// case <-r.Done:
// processResponse(r.Response, r.Error)
// }
//
// Don't forget starting the client with Client.Start() before
// calling Client.CallAsync().
func (c *Client) CallAsync(request interface{}) (*AsyncResult, error) {
return c.callAsync(request, false)
}
func (c *Client) callAsync(request interface{}, skipResponse bool) (ar *AsyncResult, err error) {
m := &AsyncResult{
request: request,
}
if !skipResponse {
m.t = time.Now()
m.done = make(chan struct{})
m.Done = m.done
}
select {
case c.requestsChan <- m:
return m, nil
default:
err = fmt.Errorf("gorpc.Client: [%s]. Requests' queue with size=%d is overflown. Try increasing Client.PendingRequests value", c.Addr, cap(c.requestsChan))
c.LogError("%s", err)
err = &ClientError{
Overflow: true,
err: err,
}
return nil, err
}
}
// Batch allows grouping and executing multiple RPCs in a single batch.
//
// Batch may be created via Client.NewBatch().
type Batch struct {
c *Client
ops []*BatchResult
opsLock sync.Mutex
}
// BatchResult is a result returned from Batch.Add*().
type BatchResult struct {
// The response can be read only after Batch.Call*() returns.
Response interface{}
// The error can be read only after Batch.Call*() returns.
// The error can be casted to ClientError.
Error error
// <-Done unblocks after Batch.Call*() returns.
// Response and Error become available after <-Done unblocks.
Done <-chan struct{}
request interface{}
ctx interface{}
done chan struct{}
}
// NewBatch creates new RPC batch.
//
// It is safe creating multiple concurrent batches from a single client.
//
// Don't forget starting the client with Client.Start() before working
// with batched RPC.
func (c *Client) NewBatch() *Batch {
return &Batch{
c: c,
}
}
// Add ads new request to the RPC batch.
//
// The order of batched RPCs execution on the server is unspecified.
//
// All the requests added to the batch are sent to the server at once
// when Batch.Call*() is called.
//
// It is safe adding multiple requests to the same batch from concurrently
// running goroutines.
func (b *Batch) Add(request interface{}) *BatchResult {
return b.add(request, false)
}
// AddSkipResponse adds new request to the RPC batch and doesn't care
// about the response.
//
// The order of batched RPCs execution on the server is unspecified.
//
// All the requests added to the batch are sent to the server at once
// when Batch.Call*() is called.
//
// It is safe adding multiple requests to the same batch from concurrently
// running goroutines.
func (b *Batch) AddSkipResponse(request interface{}) {
b.add(request, true)
}
func (b *Batch) add(request interface{}, skipResponse bool) *BatchResult {
br := &BatchResult{
request: request,
}
if !skipResponse {
br.done = make(chan struct{})
br.Done = br.done
}
b.opsLock.Lock()
b.ops = append(b.ops, br)
b.opsLock.Unlock()
return br
}
// Call calls all the RPCs added via Batch.Add().
//
// The order of batched RPCs execution on the server is unspecified.
//
// The caller may read all BatchResult contents returned from Batch.Add()
// after the Call returns.
//
// It is guaranteed that all <-BatchResult.Done channels are unblocked after
// the Call returns.
func (b *Batch) Call() error {
return b.CallTimeout(b.c.RequestTimeout)
}
// CallTimeout calls all the RPCs added via Batch.Add() and waits for
// all the RPC responses during the given timeout.
//
// The caller may read all BatchResult contents returned from Batch.Add()
// after the CallTimeout returns.
//
// It is guaranteed that all <-BatchResult.Done channels are unblocked after
// the CallTimeout returns.
func (b *Batch) CallTimeout(timeout time.Duration) error {
b.opsLock.Lock()
ops := b.ops
b.ops = nil
b.opsLock.Unlock()
results := make([]*AsyncResult, len(ops))
for i := range ops {
op := ops[i]
r, err := callAsyncRetry(b.c, op.request, op.done == nil, 5)
if err != nil {
return err
}
results[i] = r
}
t := acquireTimer(timeout)
for i := range results {
r := results[i]
op := ops[i]
if op.done == nil {
continue
}
select {
case <-r.Done:
op.Response, op.Error = r.Response, r.Error
close(op.done)
case <-t.C:
releaseTimer(t)
err := getClientTimeoutError(b.c, timeout)
for ; i < len(results); i++ {
op = ops[i]
op.Error = err
if op.done != nil {
close(op.done)
}
}
return err
}
}
releaseTimer(t)
return nil
}
func callAsyncRetry(c *Client, request interface{}, skipResponse bool, retriesCount int) (*AsyncResult, error) {
retriesCount++
for {
ar, err := c.callAsync(request, skipResponse)
if err == nil {
return ar, nil
}
if !err.(*ClientError).Overflow {
return nil, err
}
retriesCount--
if retriesCount <= 0 {
return nil, err
}
time.Sleep(10 * time.Millisecond)
}
}
// ClientError is an error Client methods can return.
type ClientError struct {
// Set if the error is timeout-related.
Timeout bool
// Set if the error is connection-related.
Connection bool
// Set if the error is server-related.
Server bool
// Set if the error is related to internal resources' overflow.
// Increase PendingRequests if you see a lot of such errors.
Overflow bool
err error
}
func (e *ClientError) Error() string {
return e.err.Error()
}
func clientHandler(c *Client) {
defer c.stopWg.Done()
var conn io.ReadWriteCloser
var err error
for {
dialChan := make(chan struct{})
go func() {
if conn, err = c.Dial(c.Addr); err != nil {
c.LogError("gorpc.Client: [%s]. Cannot establish rpc connection: [%s]", c.Addr, err)
time.Sleep(time.Second)
}
close(dialChan)
}()
select {
case <-c.clientStopChan:
return
case <-dialChan:
c.Stats.incDialCalls()
}
if err != nil {
c.Stats.incDialErrors()
continue
}
clientHandleConnection(c, conn)
}
}
func clientHandleConnection(c *Client, conn io.ReadWriteCloser) {
if c.OnConnect != nil {
newConn, err := c.OnConnect(c.Addr, conn)
if err != nil {
c.LogError("gorpc.Client: [%s]. OnConnect error: [%s]", c.Addr, err)
conn.Close()
return
}
conn = newConn
}
var buf [1]byte
if !c.DisableCompression {
buf[0] = 1
}
_, err := conn.Write(buf[:])
if err != nil {
c.LogError("gorpc.Client: [%s]. Error when writing handshake to server: [%s]", c.Addr, err)
conn.Close()
return
}
stopChan := make(chan struct{})
pendingRequests := make(map[uint64]*AsyncResult)
var pendingRequestsLock sync.Mutex
writerDone := make(chan error, 1)
go clientWriter(c, conn, pendingRequests, &pendingRequestsLock, stopChan, writerDone)
readerDone := make(chan error, 1)
go clientReader(c, conn, pendingRequests, &pendingRequestsLock, readerDone)
select {
case err = <-writerDone:
close(stopChan)
conn.Close()
<-readerDone
case err = <-readerDone:
close(stopChan)
conn.Close()
<-writerDone
case <-c.clientStopChan:
close(stopChan)
conn.Close()
<-readerDone
<-writerDone
}
if err != nil {
c.LogError("%s", err)
err = &ClientError{
Connection: true,
err: err,
}
}
for _, m := range pendingRequests {
m.Error = err
if m.done != nil {
close(m.done)
}
}
}
func clientWriter(c *Client, w io.Writer, pendingRequests map[uint64]*AsyncResult, pendingRequestsLock *sync.Mutex, stopChan <-chan struct{}, done chan<- error) {
var err error
defer func() { done <- err }()
e := newMessageEncoder(w, c.SendBufferSize, !c.DisableCompression, &c.Stats)
defer e.Close()
t := time.NewTimer(c.FlushDelay)
var flushChan <-chan time.Time
var wr wireRequest
var msgID uint64
for {
var m *AsyncResult
select {
case m = <-c.requestsChan:
default:
select {
case <-stopChan:
return
case m = <-c.requestsChan:
case <-flushChan:
if err = e.Flush(); err != nil {
err = fmt.Errorf("gorpc.Client: [%s]. Cannot flush requests to underlying stream: [%s]", c.Addr, err)
return
}
flushChan = nil
continue
}
}
if flushChan == nil {
flushChan = getFlushChan(t, c.FlushDelay)
}
if m.done == nil {
wr.ID = 0
} else {
msgID++
if msgID == 0 {
msgID = 1
}
pendingRequestsLock.Lock()
n := len(pendingRequests)
for {
if _, ok := pendingRequests[msgID]; !ok {
break
}
msgID++
}
pendingRequests[msgID] = m
pendingRequestsLock.Unlock()
if n > 10*c.PendingRequests {
err = fmt.Errorf("gorpc.Client: [%s]. The server didn't return %d responses yet. Closing server connection in order to prevent client resource leaks", c.Addr, n)
return
}
wr.ID = msgID
}
wr.Request = m.request
m.request = nil
if err = e.Encode(wr); err != nil {
err = fmt.Errorf("gorpc.Client: [%s]. Cannot send request to wire: [%s]", c.Addr, err)
return
}
wr.Request = nil
}
}
func clientReader(c *Client, r io.Reader, pendingRequests map[uint64]*AsyncResult, pendingRequestsLock *sync.Mutex, done chan<- error) {
var err error
defer func() {
if r := recover(); r != nil {
if err == nil {
err = fmt.Errorf("gorpc.Client: [%s]. Panic when reading data from server: %v", c.Addr, r)
}
}
done <- err
}()
d := newMessageDecoder(r, c.RecvBufferSize, !c.DisableCompression, &c.Stats)
defer d.Close()
var wr wireResponse
for {
if err = d.Decode(&wr); err != nil {
err = fmt.Errorf("gorpc.Client: [%s]. Cannot decode response: [%s]", c.Addr, err)
return
}
pendingRequestsLock.Lock()
m, ok := pendingRequests[wr.ID]
if ok {
delete(pendingRequests, wr.ID)
}
pendingRequestsLock.Unlock()
if !ok {
err = fmt.Errorf("gorpc.Client: [%s]. Unexpected msgID=[%d] obtained from server", c.Addr, wr.ID)
return
}
m.Response = wr.Response
wr.ID = 0
wr.Response = nil
if wr.Error != "" {
m.Error = &ClientError{
Server: true,
err: fmt.Errorf("gorpc.Client: [%s]. Server error: [%s]", c.Addr, wr.Error),
}
wr.Error = ""
}
close(m.done)
c.Stats.incRPCCalls()
c.Stats.incRPCTime(uint64(time.Since(m.t).Seconds() * 1000))
}
}