/
servant_client_info.go
97 lines (80 loc) · 1.69 KB
/
servant_client_info.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
package serve
import (
"os"
"sync"
"sync/atomic"
"github.com/yamakiller/velcro-go/network"
)
var (
clientInfoPool sync.Pool
enablePoolClientInfo int32 = 1
)
func init() {
// allow disabling by env without modifying the code and recompiling
if os.Getenv("VELCRO_DISABLE_SERVANT_CLIENT_INFO_POOL") != "" {
EnablePoolClientInfo(false)
}
}
func EnablePoolClientInfo(enable bool) {
if enable {
atomic.StoreInt32(&enablePoolClientInfo, 1)
} else {
atomic.StoreInt32(&enablePoolClientInfo, 0)
}
}
// PoolEnabled returns true if pool is enabled.
func PoolEnabledClientInfo() bool {
return atomic.LoadInt32(&enablePoolClientInfo) == 1
}
type ServantClientInfo struct {
context network.Context
message interface{}
}
func (s *ServantClientInfo) SeqId() int32 {
cid, ok := UnwrapEnvelopeSequenceId(s.message)
if !ok {
return -1
}
return cid
}
func (s *ServantClientInfo) Sender() *network.ClientID {
cid, ok := UnwrapEnvelopeSender(s.message)
if !ok {
return nil
}
return cid
}
func (s *ServantClientInfo) Message() interface{} {
return UnwrapEnvelopeMessage(s.message)
}
func (s *ServantClientInfo) zero() {
s.context = nil
if s.message == nil {
return
}
if v, ok := s.message.(*MessageEnvelope); ok {
v.Recycle()
s.message = nil
} else {
s.message = nil
}
}
func (s *ServantClientInfo) Recycle() {
if !PoolEnabledClientInfo() {
return
}
s.zero()
clientInfoPool.Put(s)
}
func init() {
clientInfoPool.New = newClientInfo
}
func NewClientInfo(ctx network.Context, message interface{}) *ServantClientInfo {
s := clientInfoPool.Get().(*ServantClientInfo)
s.context = ctx
s.message = message
return s
}
func newClientInfo() interface{} {
return &ServantClientInfo{}
}