-
Notifications
You must be signed in to change notification settings - Fork 81
Expand file tree
/
Copy pathhandler.go
More file actions
1388 lines (1167 loc) · 36.9 KB
/
Copy pathhandler.go
File metadata and controls
1388 lines (1167 loc) · 36.9 KB
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
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2020 lesismal. All rights reserved.
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
package arpc
import (
"bufio"
"context"
"fmt"
"io"
"net"
"reflect"
"strings"
"sync"
"time"
"github.com/lesismal/arpc/codec"
"github.com/lesismal/arpc/log"
"github.com/lesismal/arpc/util"
)
// DefaultHandler is the default Handler used by arpc
var DefaultHandler Handler = NewHandler()
// HandlerFunc defines message handler.
type HandlerFunc func(*Context)
// StreamHandlerFunc defines stream handler.
type StreamHandlerFunc func(*Stream)
// AsyncHandlerFunc defines callback of Client.CallAsync.
type AsyncHandlerFunc func(*Context, error)
type asyncHandler struct {
timer *time.Timer
handler AsyncHandlerFunc
}
var (
emptyAsyncHandler = asyncHandler{}
asyncHandlerPool = sync.Pool{
New: func() interface{} {
return &asyncHandler{}
},
}
)
func getAsyncHandler(t *time.Timer, h AsyncHandlerFunc) *asyncHandler {
ah := asyncHandlerPool.Get().(*asyncHandler)
ah.timer = t
ah.handler = h
return ah
}
func putAsyncHandler(ah *asyncHandler) {
*ah = emptyAsyncHandler
asyncHandlerPool.Put(ah)
}
// routerHandler saves all middleware and method/router handler funcs
// for every method by register order,
// all the funcs will be called one by one for every message.
type routerHandler struct {
async bool
handlers []HandlerFunc
}
// streamHandler saves all stream handler and middleware funcs.
// for every method by register order,
// all the funcs will be called one by one for every message.
type streamHandler struct {
async bool
handler StreamHandlerFunc
}
// Handler defines net message handler interface.
type Handler interface {
// Clone returns a copy of Handler.
Clone() Handler
// LogTag returns log tag value.
LogTag() string
// SetLogTag sets log tag.
SetLogTag(tag string)
// HandleConnected registers handler which will be called when client connected.
HandleConnected(onConnected func(*Client))
// OnConnected will be called when client is connected.
OnConnected(c *Client)
// HandleDisconnected registers handler which will be called when client is disconnected.
HandleDisconnected(onDisConnected func(*Client))
// OnDisconnected will be called when client is disconnected.
OnDisconnected(c *Client)
// MaxReconnectTimes returns client's max reconnect times.
MaxReconnectTimes() int
// SetMaxReconnectTimes sets client's max reconnect times for.
SetMaxReconnectTimes(n int)
// HandleOverstock registers handler which will be called when client send queue is overstock.
HandleOverstock(onOverstock func(c *Client, m *Message))
// OnOverstock will be called when client chSend is full.
OnOverstock(c *Client, m *Message)
// HandleMessageDone registers handler which will be called when message dropped.
HandleMessageDone(onMessageDone func(c *Client, m *Message))
// OnMessageDone will be called when message is dropped.
OnMessageDone(c *Client, m *Message)
// HandleMessageDropped registers handler which will be called when message dropped.
HandleMessageDropped(onOverstock func(c *Client, m *Message))
// OnOverstock will be called when message is dropped.
OnMessageDropped(c *Client, m *Message)
// HandleSessionMiss registers handler which will be called when async message seq not found.
HandleSessionMiss(onSessionMiss func(c *Client, m *Message))
// OnSessionMiss will be called when async message seq not found.
OnSessionMiss(c *Client, m *Message)
// HandleContextDone registers handler which will be called when message dropped.
HandleContextDone(onContextDone func(ctx *Context))
// OnContextDone will be called when message is dropped.
OnContextDone(ctx *Context)
// BeforeRecv registers handler which will be called before Recv.
BeforeRecv(h func(net.Conn) error)
// BeforeSend registers handler which will be called before Send.
BeforeSend(h func(net.Conn) error)
// BatchRecv returns BatchRecv flag.
BatchRecv() bool
// SetBatchRecv sets BatchRecv flag.
SetBatchRecv(batch bool)
// BatchSend returns BatchSend flag.
BatchSend() bool
// SetBatchSend sets BatchSend flag.
SetBatchSend(batch bool)
// AsyncWrite returns AsyncWrite flag.
AsyncWrite() bool
// SetAsyncWrite sets AsyncWrite flag.
SetAsyncWrite(async bool)
// AsyncWritev returns AsyncWritev flag.
// When enabled, the Client sends messages through a lock-protected
// [][]byte queue drained by an on-demand writer goroutine that uses
// net.Buffers (writev) instead of the chSend/sendLoop path.
AsyncWritev() bool
// SetAsyncWritev sets AsyncWritev flag.
SetAsyncWritev(async bool)
// AsyncResponse returns AsyncResponse flag.
AsyncResponse() bool
// SetAsyncResponse sets AsyncResponse flag.
SetAsyncResponse(async bool)
// WrapReader wraps net.Conn to Read data with io.Reader.
WrapReader(conn net.Conn) io.Reader
// SetReaderWrapper registers reader wrapper for net.Conn.
SetReaderWrapper(wrapper func(conn net.Conn) io.Reader)
// Recv reads a message from a client.
Recv(c *Client) (*Message, error)
// Send writes buffer data to a connection.
Send(c net.Conn, buffer []byte) (int, error)
// SendN writes multiple buffer data to a connection.
SendN(conn net.Conn, buffers net.Buffers) (int, error)
// RecvBufferSize returns client's recv buffer size.
RecvBufferSize() int
// SetRecvBufferSize sets client's recv buffer size.
SetRecvBufferSize(size int)
// SendBufferSize returns client's send buffer size.
SendBufferSize() int
// SetSendBufferSize sets client's send buffer size.
SetSendBufferSize(size int)
// ReadTimeout returns client's read timeout.
ReadTimeout() time.Duration
// SetReadTimeout sets client's read timeout.
SetReadTimeout(timeout time.Duration)
// WriteTimeout returns client's write timeout.
WriteTimeout() time.Duration
// SetWriteTimeout sets client's write timeout.
SetWriteTimeout(timeout time.Duration)
// SendQueueSize returns client's send queue channel capacity.
SendQueueSize() int
// SetSendQueueSize sets client's send queue channel capacity.
SetSendQueueSize(size int)
// StreamQueueSize returns stream queue channel capacity.
StreamQueueSize() int
// SetStreamQueueSize sets stream queue channel capacity.
SetStreamQueueSize(size int)
// MaxBodyLen returns max body length of a message.
MaxBodyLen() int
// SetMaxBodyLen sets max body length of a message.
SetMaxBodyLen(l int)
// Use registers method/router handler middleware.
Use(h HandlerFunc)
// UseCoder registers message coding middleware,
// coder.Encode will be called before message send,
// coder.Decode will be called after message recv.
UseCoder(coder MessageCoder)
// Coders returns coding middlewares.
Coders() []MessageCoder
// Handle registers method/router handler.
//
// If pass a Boolean value of "true", the handler will be called asynchronously in a new goroutine,
// Else the handler will be called synchronously in the client's reading goroutine one by one.
Handle(m string, h HandlerFunc, args ...interface{})
// Singleflight enables singleflight de-duplication of Client.Call for the
// given method. When several goroutines Call the same method with the same
// key at the same time, only one request is actually sent to the server and
// all the callers share its response, which reduces duplicated round-trips.
//
// keyFunc is optional and computes the de-dup key from the Call's req arg.
// If it is omitted(or nil), the key is req.String() when req implements
// fmt.Stringer, otherwise fmt.Sprintf("%v", req) is used.
Singleflight(method string, keyFunc ...func(req interface{}) string)
// SingleflightKey reports whether method has singleflight enabled(via
// Singleflight) and, if so, returns the de-dup key computed from req.
SingleflightKey(method string, req interface{}) (string, bool)
// Register registers all the eligible method pairs of a struct value h
// as method/router handlers, using m as the service name.
//
// For each eligible pair of methods on h:
// - The first method must be exported and have the signature:
// func (ctx context.Context, req *Request, rsp *Response)
// with no return values, where req and rsp are pointers to structs.
// - The second method must be named as the first method's name plus the
// "Binding" suffix, and must be of arpc.HandlerFunc type. It is expected
// to new the request/response pointers and call the first method.
//
// The second method(the "Binding" one) of each eligible pair is registered
// with the route name in the "Service.Method" form: m + "." + the first
// method's name (or just the method's name when m is empty).
//
// A first method that has no valid "Binding" pair is registered standalone,
// under its own name(in the same "Service.Method" form), using an
// auto-generated handler that news the request/response, binds the request,
// calls the method and writes the response.
//
// Any other exported method that is itself of arpc.HandlerFunc type
// (func(*arpc.Context)) but is not the "Binding" half of an eligible pair is
// also registered standalone, under its own name.
//
// If no method is registered, Register panics.
//
// It returns any error encountered during registration.
Register(m string, h interface{}) error
// HandleNotFound registers "" method/router handler,
// It will be called when mothod/router is not found.
HandleNotFound(h HandlerFunc)
// HandleStream registers method/router stream handler.
HandleStream(m string, h StreamHandlerFunc, args ...interface{})
// OnMessage finds method/router middlewares and handler, then call them one by one.
OnMessage(c *Client, m *Message)
// Malloc makes a buffer by size.
Malloc(size int) []byte
// HandleMalloc registers buffer maker.
HandleMalloc(f func(size int) []byte)
// Append append bytes to buffer.
Append(b []byte, more ...byte) []byte
// HandleAppend registers buffer appender.
HandleAppend(f func(b []byte, more ...byte) []byte)
// Free release a buffer.
Free([]byte)
// HandleFree registers buffer releaser.
HandleFree(f func(buf []byte))
// EnablePool registers handlers for pool operation for Context and Message and Message.Buffer
EnablePool(enable bool)
Context() (context.Context, context.CancelFunc)
SetContext(ctx context.Context, cancel context.CancelFunc)
Cancel()
// NewMessage creates a Message.
NewMessage(cmd byte, method string, v interface{}, isError bool, isAsync bool, seq uint64, codec codec.Codec, values map[interface{}]interface{}) *Message
// NewMessageWithBuffer creates a message with the buffer and manage the message by the pool.
// The buffer arg should be managed by a pool if EnablePool(true) .
NewMessageWithBuffer(buffer []byte) *Message
// SetAsyncExecutor sets executor.
SetAsyncExecutor(executor func(f func()))
// AsyncExecute executes a func
AsyncExecute(f func())
}
// handler represents a default Handler implementation.
type handler struct {
logtag string
batchRecv bool
batchSend bool
asyncWrite bool
asyncWritev bool
asyncResponse bool
recvBufferSize int
sendBufferSize int
readTimeout time.Duration
writeTimeout time.Duration
sendQueueSize int
streamQueueSize int
maxBodyLen int
maxReconnectTimes int
onConnected func(*Client)
onDisConnected func(*Client)
onOverstock func(c *Client, m *Message)
onMessageDone func(c *Client, m *Message)
onMessageDropped func(c *Client, m *Message)
onSessionMiss func(c *Client, m *Message)
onContextDone func(ctx *Context)
beforeRecv func(net.Conn) error
beforeSend func(net.Conn) error
malloc func(int) []byte
append func([]byte, ...byte) []byte
free func([]byte)
wrapReader func(conn net.Conn) io.Reader
routes map[string]*routerHandler
streams map[string]*streamHandler
// singleflights holds the methods enabled for Call singleflight de-dup,
// mapping each method to the func computing the de-dup key from the req.
singleflights map[string]func(req interface{}) string
middles []HandlerFunc
msgCoders []MessageCoder
ctx context.Context
cancel context.CancelFunc
executor func(f func())
}
func (h *handler) Clone() Handler {
cp := *h
cp.middles = make([]HandlerFunc, len(h.middles))
copy(cp.middles, h.middles)
cp.msgCoders = make([]MessageCoder, len(h.msgCoders))
copy(cp.msgCoders, h.msgCoders)
cp.routes = map[string]*routerHandler{}
for k, v := range h.routes {
rh := &routerHandler{
async: v.async,
handlers: make([]HandlerFunc, len(v.handlers)),
}
copy(rh.handlers, v.handlers)
cp.routes[k] = rh
}
cp.streams = map[string]*streamHandler{}
for k, v := range h.streams {
sh := &streamHandler{
async: v.async,
handler: v.handler,
}
cp.streams[k] = sh
}
if h.singleflights != nil {
cp.singleflights = make(map[string]func(req interface{}) string, len(h.singleflights))
for k, v := range h.singleflights {
cp.singleflights[k] = v
}
}
ctx, cancel := context.WithCancel(context.Background())
cp.ctx = ctx
cp.cancel = cancel
return &cp
}
func (h *handler) LogTag() string {
return h.logtag
}
func (h *handler) SetLogTag(tag string) {
h.logtag = tag
}
func (h *handler) HandleConnected(onConnected func(*Client)) {
h.onConnected = onConnected
}
func (h *handler) OnConnected(c *Client) {
if h.onConnected != nil {
h.onConnected(c)
}
}
func (h *handler) HandleDisconnected(onDisConnected func(*Client)) {
h.onDisConnected = onDisConnected
}
func (h *handler) OnDisconnected(c *Client) {
if h.onDisConnected != nil {
h.onDisConnected(c)
}
}
func (h *handler) MaxReconnectTimes() int {
return h.maxReconnectTimes
}
func (h *handler) SetMaxReconnectTimes(n int) {
h.maxReconnectTimes = n
}
func (h *handler) HandleOverstock(onOverstock func(c *Client, m *Message)) {
h.onOverstock = func(c *Client, m *Message) {
if onOverstock != nil {
onOverstock(c, m)
}
h.OnMessageDone(c, m)
}
}
func (h *handler) OnOverstock(c *Client, m *Message) {
if h.onOverstock != nil {
h.onOverstock(c, m)
}
}
func (h *handler) HandleMessageDropped(onMessageDropped func(c *Client, m *Message)) {
h.onMessageDropped = func(c *Client, m *Message) {
if onMessageDropped != nil {
onMessageDropped(c, m)
}
h.OnMessageDone(c, m)
}
}
func (h *handler) OnMessageDropped(c *Client, m *Message) {
if h.onMessageDropped != nil {
h.onMessageDropped(c, m)
}
}
func (h *handler) HandleMessageDone(onMessageDone func(c *Client, m *Message)) {
h.onMessageDone = onMessageDone
}
func (h *handler) OnMessageDone(c *Client, m *Message) {
if h.onMessageDone != nil && m != nil {
h.onMessageDone(c, m)
}
}
func (h *handler) HandleSessionMiss(onSessionMiss func(c *Client, m *Message)) {
h.onSessionMiss = onSessionMiss
}
func (h *handler) OnSessionMiss(c *Client, m *Message) {
if h.onSessionMiss != nil {
h.onSessionMiss(c, m)
h.OnMessageDone(c, m)
}
}
func (h *handler) HandleContextDone(onContextDone func(ctx *Context)) {
h.onContextDone = onContextDone
}
func (h *handler) OnContextDone(ctx *Context) {
if h.onContextDone != nil {
h.onContextDone(ctx)
}
}
func (h *handler) BeforeRecv(hb func(net.Conn) error) {
h.beforeRecv = hb
}
func (h *handler) BeforeSend(hs func(net.Conn) error) {
h.beforeSend = hs
}
func (h *handler) BatchRecv() bool {
return h.batchRecv
}
func (h *handler) SetBatchRecv(batch bool) {
h.batchRecv = batch
}
func (h *handler) BatchSend() bool {
return h.batchSend
}
func (h *handler) SetBatchSend(batch bool) {
h.batchSend = batch
}
func (h *handler) AsyncWrite() bool {
return h.asyncWrite
}
func (h *handler) SetAsyncWrite(async bool) {
h.asyncWrite = async
}
func (h *handler) AsyncWritev() bool {
return h.asyncWritev
}
func (h *handler) SetAsyncWritev(async bool) {
h.asyncWritev = async
}
func (h *handler) AsyncResponse() bool {
return h.asyncResponse
}
func (h *handler) SetAsyncResponse(async bool) {
h.asyncResponse = async
}
func (h *handler) WrapReader(conn net.Conn) io.Reader {
if h.wrapReader != nil {
return h.wrapReader(conn)
}
return conn
}
func (h *handler) SetReaderWrapper(wrapper func(conn net.Conn) io.Reader) {
h.wrapReader = wrapper
}
func (h *handler) RecvBufferSize() int {
return h.recvBufferSize
}
func (h *handler) SetRecvBufferSize(size int) {
h.recvBufferSize = size
}
func (h *handler) SendBufferSize() int {
return h.sendBufferSize
}
func (h *handler) SetSendBufferSize(size int) {
h.sendBufferSize = size
}
func (h *handler) ReadTimeout() time.Duration {
return h.readTimeout
}
func (h *handler) SetReadTimeout(timeout time.Duration) {
h.readTimeout = timeout
}
func (h *handler) WriteTimeout() time.Duration {
return h.writeTimeout
}
func (h *handler) SetWriteTimeout(timeout time.Duration) {
h.writeTimeout = timeout
}
func (h *handler) SendQueueSize() int {
return h.sendQueueSize
}
func (h *handler) SetSendQueueSize(size int) {
h.sendQueueSize = size
}
func (h *handler) StreamQueueSize() int {
return h.streamQueueSize
}
func (h *handler) SetStreamQueueSize(size int) {
h.streamQueueSize = size
}
func (h *handler) MaxBodyLen() int {
return h.maxBodyLen
}
func (h *handler) SetMaxBodyLen(l int) {
h.maxBodyLen = l
}
func (h *handler) Use(cb HandlerFunc) {
if cb == nil {
return
}
cbWithNext := func(ctx *Context) {
cb(ctx)
ctx.Next()
}
h.middles = append(h.middles, cbWithNext)
for k, v := range h.routes {
rh := &routerHandler{
async: v.async,
handlers: make([]HandlerFunc, len(v.handlers)+1),
}
copy(rh.handlers, v.handlers)
rh.handlers[len(v.handlers)] = cbWithNext
h.routes[k] = rh
}
}
func (h *handler) UseCoder(coder MessageCoder) {
if coder != nil {
h.msgCoders = append(h.msgCoders, coder)
}
}
func (h *handler) Coders() []MessageCoder {
return h.msgCoders
}
func (h *handler) Handle(method string, cb HandlerFunc, args ...interface{}) {
if method == "" {
panic(fmt.Errorf("empty('') method is reserved for [method not found], should use HandleNotFound to register '' handler"))
}
h.handle(method, cb, args...)
}
var (
typeContext = reflect.TypeOf((*context.Context)(nil)).Elem()
typeHandlerFunc = reflect.TypeOf(HandlerFunc(nil))
)
// bindingSuffix is the suffix of the second method's name in an eligible pair.
const bindingSuffix = "Binding"
func (h *handler) Register(m string, h2 interface{}) error {
if h2 == nil {
return fmt.Errorf("arpc: Register: nil handler")
}
hv := reflect.ValueOf(h2)
ht := hv.Type()
// route builds the "Service.Method" route name, or just the method name
// when the service name m is empty.
route := func(name string) string {
if m == "" {
return name
}
return m + "." + name
}
// First pass: find eligible first/Binding method pairs. The Binding method
// of each pair is registered under the first method's name, and is recorded
// in paired so that it is not also registered standalone in the second pass.
paired := map[string]bool{}
registered := 0
for i := 0; i < ht.NumMethod(); i++ {
method := ht.Method(i)
// Only consider exported methods, and skip the "Binding" methods
// themselves so that they are not treated as a first method.
if method.PkgPath != "" || strings.HasSuffix(method.Name, bindingSuffix) {
continue
}
// Check the first method's signature:
// func (receiver) Name(ctx context.Context, req *struct, rsp *struct)
// mt.In(0) is the receiver, so there are 4 input params and no output.
mt := method.Type
if mt.NumIn() != 4 || mt.NumOut() != 0 {
continue
}
if mt.In(1) != typeContext {
continue
}
if !isStructPtr(mt.In(2)) || !isStructPtr(mt.In(3)) {
continue
}
// Find the paired second method: Name + "Binding".
bindingName := method.Name + bindingSuffix
bindingVal := hv.MethodByName(bindingName)
if bindingVal.IsValid() && bindingVal.Type().ConvertibleTo(typeHandlerFunc) {
// Eligible pair: register the Binding method under the first
// method's name, and record it so it is not registered standalone.
cb := bindingVal.Convert(typeHandlerFunc).Interface().(HandlerFunc)
h.Handle(route(method.Name), cb)
paired[bindingName] = true
registered++
continue
}
// No valid Binding pair: register the first method standalone with an
// auto-generated handler that news the req/rsp, binds the request, calls
// the method and writes the response.
h.Handle(route(method.Name), newStructHandler(hv.Method(i), mt.In(2), mt.In(3)))
registered++
}
// Second pass: register the remaining arpc.HandlerFunc methods standalone,
// under their own name. A HandlerFunc method that was already consumed as
// the Binding of a pair in the first pass is skipped.
for i := 0; i < ht.NumMethod(); i++ {
method := ht.Method(i)
if method.PkgPath != "" || paired[method.Name] {
continue
}
// A standalone handler is a method whose bound value(receiver already
// bound) is convertible to arpc.HandlerFunc, i.e. func(*arpc.Context).
mv := hv.Method(i)
if !mv.Type().ConvertibleTo(typeHandlerFunc) {
continue
}
cb := mv.Convert(typeHandlerFunc).Interface().(HandlerFunc)
h.Handle(route(method.Name), cb)
registered++
}
if registered == 0 {
panic(fmt.Errorf("arpc: Register: no eligible method found on %v", ht))
}
return nil
}
// defaultSingleflightKey is the fallback key func used when Singleflight is
// called without a keyFunc: it uses req.String() when req is a fmt.Stringer,
// otherwise fmt.Sprintf("%v", req).
func defaultSingleflightKey(req interface{}) string {
if s, ok := req.(fmt.Stringer); ok {
return s.String()
}
return fmt.Sprintf("%v", req)
}
func (h *handler) Singleflight(method string, keyFunc ...func(req interface{}) string) {
if method == "" {
panic(fmt.Errorf("empty('') method is not allowed for Singleflight"))
}
if h.singleflights == nil {
h.singleflights = map[string]func(req interface{}) string{}
}
kf := defaultSingleflightKey
if len(keyFunc) > 0 && keyFunc[0] != nil {
kf = keyFunc[0]
}
h.singleflights[method] = kf
}
func (h *handler) SingleflightKey(method string, req interface{}) (string, bool) {
if h.singleflights == nil {
return "", false
}
kf, ok := h.singleflights[method]
if !ok {
return "", false
}
return kf(req), true
}
// isStructPtr reports whether t is a pointer to a struct.
func isStructPtr(t reflect.Type) bool {
return t.Kind() == reflect.Ptr && t.Elem().Kind() == reflect.Struct
}
// newStructHandler builds a HandlerFunc for a first-method-typed method that
// has no paired "Binding" method. fn is the bound method value with signature
// func(context.Context, reqType, rspType); reqType and rspType are pointers to
// structs. The returned handler news the request/response values, binds the
// request, calls the method(passing the arpc.Context as the context.Context),
// then writes the response.
func newStructHandler(fn reflect.Value, reqType, rspType reflect.Type) HandlerFunc {
return func(ctx *Context) {
req := reflect.New(reqType.Elem())
if err := ctx.Bind(req.Interface()); err != nil {
ctx.Error(err)
return
}
rsp := reflect.New(rspType.Elem())
fn.Call([]reflect.Value{reflect.ValueOf(ctx), req, rsp})
ctx.Write(rsp.Interface())
}
}
func (h *handler) HandleNotFound(cb HandlerFunc) {
h.handle("", cb)
}
func (h *handler) handle(method string, cb HandlerFunc, args ...interface{}) {
if h.routes == nil {
h.routes = map[string]*routerHandler{}
}
if len(method) > MaxMethodLen {
panic(fmt.Errorf("invalid method length %v(> MaxMethodLen %v)", len(method), MaxMethodLen))
}
if _, ok := h.routes[""]; !ok {
rh := &routerHandler{
async: false,
handlers: make([]HandlerFunc, len(h.middles)+1),
}
copy(rh.handlers, h.middles)
rh.handlers[len(h.middles)] = func(ctx *Context) {
ctx.Error(ErrMethodNotFound)
ctx.Next()
}
h.routes[""] = rh
}
if _, ok := h.routes[method]; ok && method != "" {
panic(fmt.Errorf("handler exist for method %v ", method))
}
async := h.AsyncResponse()
if len(args) > 0 {
if bv, ok := args[0].(bool); ok {
async = bv
}
}
rh := &routerHandler{
async: async,
handlers: make([]HandlerFunc, len(h.middles)+1),
}
copy(rh.handlers, h.middles)
rh.handlers[len(h.middles)] = func(ctx *Context) {
cb(ctx)
ctx.Next()
}
h.routes[method] = rh
}
func (h *handler) HandleStream(method string, cb StreamHandlerFunc, args ...interface{}) {
if h.streams == nil {
h.streams = map[string]*streamHandler{}
}
if len(method) > MaxMethodLen {
panic(fmt.Errorf("invalid method length %v(> MaxMethodLen %v)", len(method), MaxMethodLen))
}
if _, ok := h.streams[method]; ok && method != "" {
panic(fmt.Errorf("stream handler exist for method %v ", method))
}
async := h.AsyncResponse()
if len(args) > 0 {
if bv, ok := args[0].(bool); ok {
async = bv
}
}
rh := &streamHandler{
async: async,
handler: cb,
}
h.streams[method] = rh
}
func (h *handler) Recv(c *Client) (*Message, error) {
var (
err error
message *Message
)
if h.beforeRecv != nil {
if err = h.beforeRecv(c.Conn); err != nil {
return nil, err
}
}
if h.readTimeout > 0 {
c.Conn.SetReadDeadline(time.Now().Add(h.readTimeout))
}
_, err = io.ReadFull(c.Reader, c.Head[:])
if err != nil {
return nil, err
}
message, err = c.Head.message(h)
if err != nil {
return nil, err
}
if message.Len() >= HeadLen {
_, err = io.ReadFull(c.Reader, message.Buffer[HeaderIndexBodyLenEnd:])
}
return message, err
}
func (h *handler) Send(conn net.Conn, buffer []byte) (int, error) {
if h.beforeSend != nil {
if err := h.beforeSend(conn); err != nil {
return -1, err
}
}
if h.writeTimeout > 0 {
conn.SetWriteDeadline(time.Now().Add(h.writeTimeout))
}
n, err := conn.Write(buffer)
return n, err
}
func (h *handler) SendN(conn net.Conn, buffers net.Buffers) (int, error) {
if h.beforeSend != nil {
if err := h.beforeSend(conn); err != nil {
return -1, err
}
}
if h.writeTimeout > 0 {
conn.SetWriteDeadline(time.Now().Add(h.writeTimeout))
}
n64, err := buffers.WriteTo(conn)
return int(n64), err
}
func (h *handler) OnMessage(c *Client, msg *Message) {
defer util.Recover()
switch msg.Cmd() {
case CmdPing:
c.Pong()
return
case CmdPong:
return
}
for i := len(h.msgCoders) - 1; i >= 0; i-- {
msg = h.msgCoders[i].Decode(c, msg)
}
ml := msg.MethodLen()
if ml <= 0 || ml > MaxMethodLen || ml > (msg.Len()-HeadLen) {
log.Warn("%v OnMessage: invalid request method length %v, dropped", h.LogTag(), ml)
return
}
cmd := msg.Cmd()
switch cmd {
case CmdRequest, CmdNotify:
method := msg.method()
if rh, ok := h.routes[method]; ok {
ctx := newContext(c, msg, rh.handlers)
if !rh.async {
ctx.Next()
h.OnContextDone(ctx)
} else {
h.AsyncExecute(func() {
ctx.Next()
h.OnContextDone(ctx)
})
}
} else {
if rh, ok = h.routes[""]; ok {
ctx := newContext(c, msg, rh.handlers)
ctx.Next()
h.OnContextDone(ctx)
}
if cmd == CmdRequest {
log.Warn("%v OnMessage: invalid Call with method: [%v], no handler", h.LogTag(), method)
} else {
log.Warn("%v OnMessage: invalid Notify with method: [%v], no handler", h.LogTag(), method)
}
}
case CmdResponse:
if !msg.IsAsync() {
seq := msg.Seq()
session, ok := c.getSession(seq)
if ok {
session.done <- msg
} else {
h.OnSessionMiss(c, msg)
log.Warn("%v OnMessage: session not exist or expired", h.LogTag())
}