-
Notifications
You must be signed in to change notification settings - Fork 411
/
session.go
1102 lines (1005 loc) · 31.2 KB
/
session.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
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 2015-2019 HenryLee. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package erpc
import (
"context"
"encoding/json"
"fmt"
"io"
"net"
"strconv"
"sync"
"sync/atomic"
"time"
"github.com/andeya/erpc/v7/codec"
"github.com/andeya/erpc/v7/socket"
"github.com/andeya/erpc/v7/utils"
"github.com/andeya/goutil"
"github.com/andeya/goutil/coarsetime"
)
type (
// PreSession a connection session that has not started reading goroutine.
PreSession interface {
// Peer returns the peer.
Peer() Peer
// LocalAddr returns the local network address.
LocalAddr() net.Addr
// RemoteAddr returns the remote network address.
RemoteAddr() net.Addr
// Swap returns custom data swap of the session(socket).
Swap() goutil.Map
// SetID sets the session id.
SetID(newID string)
// ControlFD invokes f on the underlying connection's file
// descriptor or handle.
// The file descriptor fd is guaranteed to remain valid while
// f executes but not after f returns.
ControlFD(f func(fd uintptr)) error
// ModifySocket modifies the socket.
// NOTE:
// The connection fd is not allowed to change!
// Inherit the previous session id and custom data swap;
// If modifiedConn!=nil, reset the net.Conn of the socket;
// If newProtoFunc!=nil, reset the ProtoFunc of the socket.
ModifySocket(fn func(conn net.Conn) (modifiedConn net.Conn, newProtoFunc ProtoFunc))
// GetProtoFunc returns the ProtoFunc
GetProtoFunc() ProtoFunc
// PreSend temporarily sends message when the session is just builded,
// do not execute other plugins.
// NOTE:
// Cannot be called during the Non-PostDial and Non-PostAccept phase;
// Does not support automatic redial after disconnection;
// Recommend to reuse unused Message: PutMessage(input).
PreSend(mtype byte, serviceMethod string, body interface{}, stat *Status, setting ...MessageSetting) (opStat *Status)
// PreReceive temporarily receives message when the session is just builded,
// do not execute other plugins.
// NOTE:
// Cannot be called during the Non-PostDial and Non-PostAccept phase;
// Does not support automatic redial after disconnection;
// Recommend to reuse unused Message: PutMessage(input).
PreReceive(newArgs NewBodyFunc, ctx ...context.Context) (input Message)
// PreCall temporarily sends TypeCall message and receives message,
// when the session is just builded, do not execute other plugins.
// NOTE:
// Cannot be called during the Non-PostDial and Non-PostAccept phase;
// The reply parameter is the body receiver;
// The external setting seq is invalid, the internal will be forced to set;
// Does not support automatic redial after disconnection.
PreCall(serviceMethod string, args, reply interface{}, callSetting ...MessageSetting) (opStat *Status)
// PreReply temporarily sends TypeReply message when the session is just builded,
// do not execute other plugins.
// NOTE:
// Cannot be called during the Non-PostDial and Non-PostAccept phase;
// The external setting seq is invalid, the internal will be forced to set;
// Does not support automatic redial after disconnection.
PreReply(req Message, body interface{}, stat *Status, setting ...MessageSetting) (opStat *Status)
// RawPush sends a TypePush message without executing other plugins.
// NOTE:
// The external setting seq is invalid, the internal will be forced to set;
// Does not support automatic redial after disconnection.
RawPush(serviceMethod string, args interface{}, setting ...MessageSetting) (opStat *Status)
// SessionAge returns the session max age.
SessionAge() time.Duration
// ContextAge returns CALL or PUSH context max age.
ContextAge() time.Duration
// SetSessionAge sets the session max age.
SetSessionAge(duration time.Duration)
// SetContextAge sets CALL or PUSH context max age.
SetContextAge(duration time.Duration)
// Logger logger interface
Logger
}
// BaseSession a connection session with the common method set.
BaseSession interface {
// Peer returns the peer.
Peer() Peer
// ID returns the session id.
ID() string
// LocalAddr returns the local network address.
LocalAddr() net.Addr
// RemoteAddr returns the remote network address.
RemoteAddr() net.Addr
// Swap returns custom data swap of the session(socket).
Swap() goutil.Map
// Logger logger interface
Logger
}
// CtxSession a connection session that can be used in the handler context.
CtxSession interface {
// ID returns the session id.
ID() string
// LocalAddr returns the local network address.
LocalAddr() net.Addr
// RemoteAddr returns the remote network address.
RemoteAddr() net.Addr
// Swap returns custom data swap of the session(socket).
Swap() goutil.Map
// CloseNotify returns a channel that closes when the connection has gone away.
CloseNotify() <-chan struct{}
// Health checks if the session is usable.
Health() bool
// AsyncCall sends a message and receives reply asynchronously.
// If the is []byte or *[]byte type, it can automatically fill in the body codec name.
AsyncCall(
serviceMethod string,
args interface{},
result interface{},
callCmdChan chan<- CallCmd,
setting ...MessageSetting,
) CallCmd
// Call sends a message and receives reply.
// NOTE:
// If the args is []byte or *[]byte type, it can automatically fill in the body codec name;
// If the session is a client role and PeerConfig.RedialTimes>0, it is automatically re-called once after a failure.
Call(serviceMethod string, args interface{}, result interface{}, setting ...MessageSetting) CallCmd
// Push sends a message of TypePush type, but do not receives reply.
// NOTE:
// If the args is []byte or *[]byte type, it can automatically fill in the body codec name;
// If the session is a client role and PeerConfig.RedialTimes>0, it is automatically re-called once after a failure.
Push(serviceMethod string, args interface{}, setting ...MessageSetting) *Status
// SessionAge returns the session max age.
SessionAge() time.Duration
// ContextAge returns CALL or PUSH context max age.
ContextAge() time.Duration
// Logger logger interface
Logger
}
// Session a connection session.
Session interface {
// Peer returns the peer.
Peer() Peer
// SetID sets the session id.
SetID(newID string)
// Close closes the session.
Close() error
CtxSession
}
)
var (
_ PreSession = new(session)
_ BaseSession = new(session)
_ CtxSession = new(session)
_ Session = new(session)
)
type session struct {
peer *peer
getCallHandler, getPushHandler func(serviceMethodPath string) (*Handler, bool)
timeNow func() int64
callCmdMap goutil.Map
protoFuncs []ProtoFunc
socket socket.Socket
closeNotifyCh chan struct{} // closeNotifyCh is the channel returned by CloseNotify.
writeLock sync.Mutex
graceCtxWaitGroup sync.WaitGroup
graceCtxMutex sync.Mutex
graceCallCmdWaitGroup sync.WaitGroup
sessionAge time.Duration
contextAge time.Duration
sessionAgeLock sync.RWMutex
contextAgeLock sync.RWMutex
lock sync.RWMutex
redialForClientLocked func() bool // only for client role
seq int32
status int32
didCloseNotify int32
}
func newSession(peer *peer, conn net.Conn, protoFuncs []ProtoFunc) *session {
var s = &session{
peer: peer,
getCallHandler: peer.router.subRouter.getCall,
getPushHandler: peer.router.subRouter.getPush,
timeNow: peer.timeNow,
protoFuncs: protoFuncs,
status: statusPreparing,
socket: socket.NewSocket(conn, protoFuncs...),
closeNotifyCh: make(chan struct{}),
callCmdMap: goutil.AtomicMap(),
sessionAge: peer.defaultSessionAge,
contextAge: peer.defaultContextAge,
}
return s
}
// NOTE: Do not change the order
const (
statusPreparing int32 = iota
statusOk
statusActiveClosing
statusActiveClosed
statusPassiveClosing
statusPassiveClosed
statusRedialing
statusRedialFailed
)
func (s *session) changeStatus(stat int32) {
atomic.StoreInt32(&s.status, stat)
}
func (s *session) tryChangeStatus(to int32, fromList ...int32) (changed bool) {
for _, from := range fromList {
if atomic.CompareAndSwapInt32(&s.status, from, to) {
return true
}
}
return false
}
func (s *session) checkStatus(checkList ...int32) bool {
stat := atomic.LoadInt32(&s.status)
for _, v := range checkList {
if v == stat {
return true
}
}
return false
}
func (s *session) getStatus() int32 {
return atomic.LoadInt32(&s.status)
}
func (s *session) goonRead() bool {
return s.checkStatus(statusOk, statusActiveClosing)
}
func (s *session) notifyClosed() {
if atomic.CompareAndSwapInt32(&s.didCloseNotify, 0, 1) {
close(s.closeNotifyCh)
}
}
// CloseNotify returns a channel that closes when the connection has gone away.
func (s *session) CloseNotify() <-chan struct{} {
return s.closeNotifyCh
}
// IsActiveClosed returns whether the connection has been closed, and is actively closed.
func (s *session) IsActiveClosed() bool {
return s.checkStatus(statusActiveClosed)
}
// IsPassiveClosed returns whether the connection has been closed, and is passively closed.
func (s *session) IsPassiveClosed() bool {
return s.checkStatus(statusPassiveClosed)
}
// Health checks if the session is usable.
func (s *session) Health() bool {
status := s.getStatus()
if status == statusOk {
return true
}
if s.redialForClientLocked == nil {
return false
}
if status == statusPassiveClosed {
return true
}
return false
}
func (s *session) graceCtxWait() {
s.graceCtxMutex.Lock()
s.graceCtxWaitGroup.Wait()
s.graceCtxMutex.Unlock()
}
// Peer returns the peer.
func (s *session) Peer() Peer {
return s.peer
}
// ID returns the session id.
func (s *session) ID() string {
return s.socket.ID()
}
// SetID sets the session id.
func (s *session) SetID(newID string) {
oldID := s.ID()
if oldID == newID {
return
}
s.socket.SetID(newID)
hub := s.peer.sessHub
hub.set(s)
hub.delete(oldID)
Tracef("session changes id: %s -> %s", oldID, newID)
}
// ControlFD invokes f on the underlying connection's file
// descriptor or handle.
// The file descriptor fd is guaranteed to remain valid while
// f executes but not after f returns.
func (s *session) ControlFD(f func(fd uintptr)) error {
s.lock.RLock()
defer s.lock.RUnlock()
return s.socket.ControlFD(f)
}
func (s *session) getConn() net.Conn {
return s.socket.Raw()
}
// ModifySocket modifies the socket.
// NOTE:
// The connection fd is not allowed to change!
// Inherit the previous session id and custom data swap;
// If modifiedConn!=nil, reset the net.Conn of the socket;
// If newProtoFunc!=nil, reset the ProtoFunc of the socket.
func (s *session) ModifySocket(fn func(conn net.Conn) (modifiedConn net.Conn, newProtoFunc ProtoFunc)) {
conn := s.getConn()
modifiedConn, newProtoFunc := fn(conn)
isModifiedConn := modifiedConn != nil
isNewProtoFunc := newProtoFunc != nil
if isNewProtoFunc {
s.protoFuncs = s.protoFuncs[:0]
s.protoFuncs = append(s.protoFuncs, newProtoFunc)
}
if !isModifiedConn && !isNewProtoFunc {
return
}
var pub goutil.Map
if s.socket.SwapLen() > 0 {
pub = s.socket.Swap()
}
id := s.ID()
s.socket.Reset(modifiedConn, s.protoFuncs...)
s.socket.Swap(pub) // set the old swap
s.socket.SetID(id)
}
// GetProtoFunc returns the ProtoFunc
func (s *session) GetProtoFunc() ProtoFunc {
if len(s.protoFuncs) > 0 && s.protoFuncs[0] != nil {
return s.protoFuncs[0]
}
return socket.DefaultProtoFunc()
}
// LocalAddr returns the local network address.
func (s *session) LocalAddr() net.Addr {
return s.socket.LocalAddr()
}
// RemoteAddr returns the remote network address.
func (s *session) RemoteAddr() net.Addr {
return s.socket.RemoteAddr()
}
// SessionAge returns the session max age.
func (s *session) SessionAge() time.Duration {
s.sessionAgeLock.RLock()
age := s.sessionAge
s.sessionAgeLock.RUnlock()
return age
}
// SetSessionAge sets the session max age.
func (s *session) SetSessionAge(duration time.Duration) {
s.sessionAgeLock.Lock()
s.sessionAge = duration
if duration > 0 {
s.socket.SetReadDeadline(coarsetime.CeilingTimeNow().Add(duration))
} else {
s.socket.SetReadDeadline(time.Time{})
}
s.sessionAgeLock.Unlock()
}
// ContextAge returns CALL or PUSH context max age.
func (s *session) ContextAge() time.Duration {
s.contextAgeLock.RLock()
age := s.contextAge
s.contextAgeLock.RUnlock()
return age
}
// SetContextAge sets CALL or PUSH context max age.
func (s *session) SetContextAge(duration time.Duration) {
s.contextAgeLock.Lock()
s.contextAge = duration
s.contextAgeLock.Unlock()
}
// PreSend temporarily sends message when the session is just builded,
// do not execute other plugins.
// NOTE:
//
// Cannot be called during the Non-PostDial and Non-PostAccept phase;
// Does not support automatic redial after disconnection;
// Recommend to reuse unused Message: PutMessage(input).
func (s *session) PreSend(mtype byte, serviceMethod string, body interface{}, stat *Status, setting ...MessageSetting) (opStat *Status) {
if !s.checkStatus(statusPreparing) {
return statUnpreparedError
}
var output Message
defer func() {
if output != nil {
socket.PutMessage(output)
}
if p := recover(); p != nil {
opStat = statBadMessage.Copy(p, 3)
}
}()
output, opStat = s.send(mtype, 0, serviceMethod, body, stat, setting)
return opStat
}
func (s *session) send(mtype byte, seq int32, serviceMethod string, body interface{}, stat *Status, setting []MessageSetting) (Message, *Status) {
output := socket.GetMessage(setting...)
output.SetMtype(mtype)
if seq == 0 {
seq = atomic.AddInt32(&s.seq, 1)
}
output.SetSeq(seq)
if output.BodyCodec() == codec.NilCodecID {
output.SetBodyCodec(s.peer.defaultBodyCodec)
}
if len(serviceMethod) > 0 {
output.SetServiceMethod(serviceMethod)
}
if body != nil {
output.SetBody(body)
}
if !stat.OK() {
output.SetStatus(stat)
}
return output, s.doSend(output)
}
func (s *session) doSend(output Message) *Status {
if age := s.ContextAge(); age > 0 {
ctxTimout, _ := context.WithTimeout(output.Context(), age)
socket.WithContext(ctxTimout)(output)
}
s.writeLock.Lock()
defer s.writeLock.Unlock()
ctx := output.Context()
select {
case <-ctx.Done():
return statWriteFailed.Copy(ctx.Err())
default:
deadline, _ := ctx.Deadline()
s.socket.SetWriteDeadline(deadline)
err := s.socket.WriteMessage(output)
if err == nil {
return nil
}
if err == io.EOF || err == socket.ErrProactivelyCloseSocket {
return statConnClosed
}
Debugf("write error: %s", err.Error())
return statWriteFailed.Copy(err)
}
}
var statUnpreparedError = statInvalidOpError.Copy("Cannot be called during the Non-PostDial and Non-PostAccept phase")
// PreReceive temporarily receives message when the session is just builded,
// do not execute other plugins.
// NOTE:
//
// Cannot be called during the Non-PostDial and Non-PostAccept phase;
// Does not support automatic redial after disconnection;
// Recommend to reuse unused Message: PutMessage(input).
func (s *session) PreReceive(newArgs NewBodyFunc, ctx ...context.Context) (input Message) {
if len(ctx) > 0 {
input = socket.GetMessage(WithContext(ctx[0]))
} else {
input = socket.GetMessage()
}
if !s.checkStatus(statusPreparing) {
input.SetStatus(statUnpreparedError)
return input
}
input.SetNewBody(newArgs)
defer func() {
if p := recover(); p != nil {
input.SetStatus(statBadMessage.Copy(p, 3))
}
}()
if age := s.ContextAge(); age > 0 {
ctxTimout, _ := context.WithTimeout(input.Context(), age)
socket.WithContext(ctxTimout)(input)
}
deadline, _ := input.Context().Deadline()
s.socket.SetReadDeadline(deadline)
if err := s.socket.ReadMessage(input); err != nil {
input.SetStatus(statConnClosed.Copy(err))
}
return input
}
// PreCall temporarily sends TypeCall message and receives message,
// when the session is just builded, do not execute other plugins.
// NOTE:
//
// Cannot be called during the Non-PostDial and Non-PostAccept phase;
// The reply parameter is the body receiver;
// The external setting seq is invalid, the internal will be forced to set;
// Does not support automatic redial after disconnection.
func (s *session) PreCall(serviceMethod string, args, reply interface{}, callSetting ...MessageSetting) (opStat *Status) {
if !s.checkStatus(statusPreparing) {
return statUnpreparedError
}
defer func() {
if p := recover(); p != nil {
opStat = statBadMessage.Copy(p, 3)
}
}()
output, opStat := s.send(TypeCall, 0, serviceMethod, args, nil, callSetting)
if !opStat.OK() {
socket.PutMessage(output)
return opStat
}
ctx := output.Context()
socket.PutMessage(output)
return s.PreReceive(func(Header) interface{} { return reply }, ctx).Status()
}
// PreReply temporarily sends TypeReply message when the session is just builded,
// do not execute other plugins.
// NOTE:
//
// Cannot be called during the Non-PostDial and Non-PostAccept phase;
// The external setting seq is invalid, the internal will be forced to set;
// Does not support automatic redial after disconnection.
func (s *session) PreReply(req Message, body interface{}, stat *Status, setting ...MessageSetting) (opStat *Status) {
if !s.checkStatus(statusPreparing) {
return statUnpreparedError
}
var output Message
defer func() {
if output != nil {
socket.PutMessage(output)
}
if p := recover(); p != nil {
opStat = statBadMessage.Copy(p, 3)
}
}()
output, opStat = s.send(TypeReply, req.Seq(), req.ServiceMethod(), body, stat, setting)
return opStat
}
// RawPush sends a TypePush message without executing other plugins.
// NOTE:
//
// The external setting seq is invalid, the internal will be forced to set;
// Does not support automatic redial after disconnection.
func (s *session) RawPush(serviceMethod string, args interface{}, setting ...MessageSetting) (opStat *Status) {
var output Message
defer func() {
if output != nil {
socket.PutMessage(output)
}
if p := recover(); p != nil {
opStat = statBadMessage.Copy(p, 3)
}
}()
output, opStat = s.send(TypePush, 0, serviceMethod, args, nil, setting)
return opStat
}
// Push sends a message of TypePush type, but do not receives reply.
// NOTE:
// If the args is []byte or *[]byte type, it can automatically fill in the body codec name;
// If the session is a client role and PeerConfig.RedialTimes>0, it is automatically re-called once after a failure.
func (s *session) Push(serviceMethod string, args interface{}, setting ...MessageSetting) *Status {
ctx := s.peer.getContext(s, true)
defer func() {
s.peer.putContext(ctx, true)
if p := recover(); p != nil {
Errorf("panic:%v\n%s", p, goutil.PanicTrace(2))
}
}()
ctx.start = s.timeNow()
output := ctx.output
output.SetMtype(TypePush)
output.SetServiceMethod(serviceMethod)
output.SetBody(args)
for _, fn := range setting {
if fn != nil {
fn(output)
}
}
output.SetSeq(atomic.AddInt32(&s.seq, 1))
if output.BodyCodec() == codec.NilCodecID {
output.SetBodyCodec(s.peer.defaultBodyCodec)
}
if age := s.ContextAge(); age > 0 {
ctxTimout, _ := context.WithTimeout(output.Context(), age)
socket.WithContext(ctxTimout)(output)
}
stat := s.peer.pluginContainer.preWritePush(ctx)
if !stat.OK() {
return stat
}
var usedConn net.Conn
W:
if usedConn, stat = s.write(output); !stat.OK() {
if stat == statConnClosed && s.redialForClient(usedConn) {
goto W
}
return stat
}
if enablePrintRunLog() {
s.printRunLog("", time.Duration(s.timeNow()-ctx.start), nil, output, typePushLaunch)
}
s.peer.pluginContainer.postWritePush(ctx)
return nil
}
// AsyncCall sends a message and receives reply asynchronously.
// NOTE:
// If the args is []byte or *[]byte type, it can automatically fill in the body codec name;
// If the session is a client role and PeerConfig.RedialTimes>0, it is automatically re-called once after a failure.
func (s *session) AsyncCall(
serviceMethod string,
args interface{},
result interface{},
callCmdChan chan<- CallCmd,
setting ...MessageSetting,
) CallCmd {
if callCmdChan == nil {
callCmdChan = make(chan CallCmd, 10) // buffered.
} else {
// If caller passes callCmdChan != nil, it must arrange that
// callCmdChan 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(callCmdChan) == 0 {
Panicf("*session.AsyncCall(): callCmdChan channel is unbuffered")
}
}
output := socket.NewMessage()
output.SetServiceMethod(serviceMethod)
output.SetBody(args)
output.SetMtype(TypeCall)
for _, fn := range setting {
if fn != nil {
fn(output)
}
}
seq := atomic.AddInt32(&s.seq, 1)
output.SetSeq(seq)
if output.BodyCodec() == codec.NilCodecID {
output.SetBodyCodec(s.peer.defaultBodyCodec)
}
if age := s.ContextAge(); age > 0 {
ctxTimout, _ := context.WithTimeout(output.Context(), age)
socket.WithContext(ctxTimout)(output)
}
cmd := &callCmd{
sess: s,
output: output,
result: result,
callCmdChan: callCmdChan,
doneChan: make(chan struct{}),
start: s.timeNow(),
swap: goutil.RwMap(),
}
// count call-launch
s.graceCallCmdWaitGroup.Add(1)
if s.socket.SwapLen() > 0 {
s.socket.Swap().Range(func(key, value interface{}) bool {
cmd.swap.Store(key, value)
return true
})
}
cmd.mu.Lock()
defer cmd.mu.Unlock()
s.callCmdMap.Store(seq, cmd)
defer func() {
if p := recover(); p != nil {
Errorf("panic:%v\n%s", p, goutil.PanicTrace(2))
}
}()
cmd.stat = s.peer.pluginContainer.preWriteCall(cmd)
if !cmd.stat.OK() {
cmd.done()
return cmd
}
var usedConn net.Conn
W:
if usedConn, cmd.stat = s.write(output); !cmd.stat.OK() {
if cmd.stat == statConnClosed && s.redialForClient(usedConn) {
goto W
}
cmd.done()
return cmd
}
s.peer.pluginContainer.postWriteCall(cmd)
return cmd
}
// Call sends a message and receives reply.
// NOTE:
// If the args is []byte or *[]byte type, it can automatically fill in the body codec name;
// If the session is a client role and PeerConfig.RedialTimes>0, it is automatically re-called once after a failure.
func (s *session) Call(serviceMethod string, args interface{}, result interface{}, setting ...MessageSetting) CallCmd {
callCmd := s.AsyncCall(serviceMethod, args, result, make(chan CallCmd, 1), setting...)
<-callCmd.Done()
return callCmd
}
// Swap returns custom data swap of the session(socket).
func (s *session) Swap() goutil.Map {
return s.socket.Swap()
}
// Close closes the session.
func (s *session) Close() error {
s.lock.Lock()
defer s.lock.Unlock()
return s.closeLocked()
}
func (s *session) closeLocked() error {
if !s.tryChangeStatus(statusActiveClosing, statusOk, statusPreparing) {
return nil
} // readDisconnected is being called
s.peer.sessHub.delete(s.ID())
s.notifyClosed()
s.graceCtxWait()
s.graceCallCmdWaitGroup.Wait()
s.changeStatus(statusActiveClosed)
err := s.socket.Close()
s.peer.pluginContainer.postDisconnect(s)
return err
}
func (s *session) readDisconnected(oldConn net.Conn, err error) {
status := s.getStatus()
switch status {
case statusPassiveClosed, statusActiveClosed, statusPassiveClosing:
return
case statusActiveClosing:
default:
s.changeStatus(statusPassiveClosing)
}
s.peer.sessHub.delete(s.ID())
var reason string
if err != nil && err != socket.ErrProactivelyCloseSocket {
if errStr := err.Error(); errStr != "EOF" {
reason = errStr
Debugf("disconnect(%s) when reading: %T %s", s.RemoteAddr().String(), err, errStr)
}
}
s.graceCtxWait()
// cancel the callCmd that is waiting for a reply
s.callCmdMap.Range(func(_, v interface{}) bool {
callCmd := v.(*callCmd)
callCmd.mu.Lock()
if !callCmd.hasReply() && callCmd.stat.OK() {
callCmd.cancel(reason)
}
callCmd.mu.Unlock()
return true
})
if status == statusActiveClosing {
return
}
s.socket.Close()
if !s.redialForClient(oldConn) {
s.changeStatus(statusPassiveClosed)
s.notifyClosed()
s.peer.pluginContainer.postDisconnect(s)
}
}
func (s *session) redialForClient(oldConn net.Conn) bool {
if s.redialForClientLocked == nil {
return false
}
s.lock.Lock()
defer s.lock.Unlock()
// Avoid repeated calls from write and readDisconnected methods
if oldConn != s.getConn() {
return true
}
if s.tryChangeStatus(statusRedialing, statusOk, statusPassiveClosing, statusPassiveClosed, statusRedialFailed) {
return s.redialForClientLocked()
}
return false
}
func (s *session) startReadAndHandle() {
var withContext MessageSetting
if readTimeout := s.SessionAge(); readTimeout > 0 {
s.socket.SetReadDeadline(coarsetime.CeilingTimeNow().Add(readTimeout))
ctxTimout, _ := context.WithTimeout(context.Background(), readTimeout)
withContext = socket.WithContext(ctxTimout)
} else {
s.socket.SetReadDeadline(time.Time{})
withContext = socket.WithContext(nil)
}
var (
err error
usedConn = s.getConn()
)
defer func() {
if p := recover(); p != nil {
err = fmt.Errorf("panic:%v\n%s", p, goutil.PanicTrace(2))
}
s.readDisconnected(usedConn, err)
}()
// read call, call reply or push
for s.goonRead() {
var ctx = s.peer.getContext(s, false)
withContext(ctx.input)
if s.peer.pluginContainer.preReadHeader(ctx) != nil {
s.peer.putContext(ctx, false)
return
}
err = s.socket.ReadMessage(ctx.input)
if (err != nil && ctx.GetBodyCodec() == codec.NilCodecID) || !s.goonRead() {
s.peer.putContext(ctx, false)
return
}
if err != nil {
ctx.stat = statBadMessage.Copy(err)
}
s.graceCtxWaitGroup.Add(1)
if !Go(func() {
defer s.peer.putContext(ctx, true)
ctx.handle()
}) {
s.peer.putContext(ctx, true)
}
}
}
func (s *session) write(message Message) (net.Conn, *Status) {
usedConn := s.getConn()
status := s.getStatus()
if !(status == statusOk || (status == statusActiveClosing && message.Mtype() == TypeReply)) {
return usedConn, statConnClosed
}
var (
err error
ctx = message.Context()
deadline, _ = ctx.Deadline()
)
select {
case <-ctx.Done():
err = ctx.Err()
goto ERR
default:
}
s.writeLock.Lock()
defer s.writeLock.Unlock()
select {
case <-ctx.Done():
err = ctx.Err()
goto ERR
default:
s.socket.SetWriteDeadline(deadline)
err = s.socket.WriteMessage(message)
}
if err == nil {
return usedConn, nil
}
if err == io.EOF || err == socket.ErrProactivelyCloseSocket {
return usedConn, statConnClosed
}
Debugf("write error: %s", err.Error())
ERR:
return usedConn, statWriteFailed.Copy(err)
}
// SessionHub sessions hub
type SessionHub struct {
// key: session id (ip, name and so on)
// value: *session
sessions goutil.Map
}
// newSessionHub creates a new sessions hub.
func newSessionHub() *SessionHub {
chub := &SessionHub{
sessions: goutil.AtomicMap(),
}
return chub
}
// set sets a *session.
func (sh *SessionHub) set(sess *session) {
_sess, loaded := sh.sessions.LoadOrStore(sess.ID(), sess)
if !loaded {
return
}
sh.sessions.Store(sess.ID(), sess)
if oldSess := _sess.(*session); sess != oldSess {
oldSess.Close()
}
}
// get gets *session by id.
// If second returned arg is false, mean the *session is not found.
func (sh *SessionHub) get(id string) (*session, bool) {
_sess, ok := sh.sessions.Load(id)
if !ok {
return nil, false
}
return _sess.(*session), true
}
// rangeCallback calls f sequentially for each id and *session present in the session hub.
// If fn returns false, stop traversing.
func (sh *SessionHub) rangeCallback(fn func(*session) bool) {
sh.sessions.Range(func(key, value interface{}) bool {
return fn(value.(*session))
})
}
// random gets a *session randomly.
// If second returned arg is false, mean no *session is exist.
func (sh *SessionHub) random() (*session, bool) {
_, sess, exist := sh.sessions.Random()
if !exist {
return nil, false
}
return sess.(*session), true
}
// len returns the length of the session hub.
// NOTE: the count implemented using sync.Map may be inaccurate.
func (sh *SessionHub) len() int {
return sh.sessions.Len()