/
sess.go
280 lines (252 loc) · 5.32 KB
/
sess.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
package stcp
import (
"github.com/pinealctx/neptune/syncx/pipe/q"
"github.com/pinealctx/neptune/ulog"
"go.uber.org/atomic"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"io"
"net"
"sync"
"time"
)
// NetIO : net io
type NetIO interface {
//Set set session related value
Set(v interface{})
//Get get session related value
Get() interface{}
//SetRemoteAddr :
SetRemoteAddr(addr string)
//RemoteAddr :
RemoteAddr() string
//Send : send bytes
Send(bs []byte) error
//Read : read specific bytes
Read(bs []byte) error
//Close : close session
Close()
//Logger : get uber logger
Logger() *ulog.Logger
//RemoteZap : for uber log
RemoteZap() zap.Field
//KeyZaps : for uber log, key info
KeyZaps(ext ...zap.Field) []zap.Field
}
// IKeyZap : 做调试用的信息
type IKeyZap interface {
//KeyZaps : for uber log, key info
KeyZaps(ext ...zap.Field) []zap.Field
}
// Session session
// SessionMgr的handler作为缺省的handler
// rh作为自己独立的handler
// 优先使用rh,如果rh为空,使用SessionMgr
type Session struct {
//连接
conn net.Conn
//rh
rh ISession
//base handler
b *SessionMgr
//所带字段
value atomic.Value
//发送q
//queue -- actually the queue is bytes
sendQ *q.Q
//remote addr
remoteAddr atomic.String
//start once
startOnce sync.Once
//exit once
exitOnce sync.Once
}
// NewSession :
func NewSession(b *SessionMgr, conn net.Conn) *Session {
return &Session{
b: b,
conn: conn,
sendQ: q.NewQ(),
}
}
// Start :
func (s *Session) Start() {
s.startOnce.Do(func() {
s.b.count.Inc()
go s.loopSend()
go s.loopReceive()
})
}
// UpdateHandler : update handler
func (s *Session) UpdateHandler(rh ISession) {
s.rh = rh
}
// Set :
func (s *Session) Set(v interface{}) {
s.value.Store(v)
}
// Get :
func (s *Session) Get() interface{} {
return s.value.Load()
}
// SetRemoteAddr :
func (s *Session) SetRemoteAddr(addr string) {
s.remoteAddr.Store(addr)
}
// RemoteAddr :
func (s *Session) RemoteAddr() string {
return absRemoteAddr(s.remoteAddr, s.conn)
}
// Send : send bytes, put bytes to queue, not send directly
func (s *Session) Send(bs []byte) error {
return s.sendQ.AddReq(bs)
}
// Read : read specific bytes
func (s *Session) Read(bs []byte) error {
var _, err = io.ReadFull(s.conn, bs)
return err
}
// Close : close session
// use close send msg queue to exit loop read/write go routine
func (s *Session) Close() {
s.sendQ.Close()
}
// Logger : get logger
func (s *Session) Logger() *ulog.Logger {
return s.b.Logger()
}
// RemoteZap : for uber log
func (s *Session) RemoteZap() zap.Field {
return zap.String("session.Addr", s.RemoteAddr())
}
// KeyZaps : for uber log
func (s *Session) KeyZaps(ext ...zap.Field) []zap.Field {
return absSessionInfo(s.value, ext...)
}
// loop send
func (s *Session) loopSend() {
var (
err error
qItem interface{}
bs []byte
ok bool
)
defer s.recovery()
defer s.quit()
for {
qItem, err = s.sendQ.PopAnyway()
if err != nil {
s.b.Logger().Debug("quit.in.send.q", s.KeyZaps(zap.Error(err))...)
return
}
bs, ok = qItem.([]byte)
if !ok || len(bs) == 0 {
s.b.Logger().Error("invalid.send.q", zap.Any("q", qItem))
return
}
err = s.send(bs)
if err != nil {
s.loggerSendReadErr("connection.send.fail", err)
return
}
}
}
// loop receive
func (s *Session) loopReceive() {
defer s.recovery()
defer s.quit()
for {
var err = s.conn.SetReadDeadline(time.Now().Add(s.b.readTimeout))
if err != nil {
s.b.Logger().Error("set.read.conn.deadline", zap.Error(err), s.RemoteZap())
return
}
if s.rh != nil {
err = s.rh.Read(s)
} else {
err = s.b.rh.Read(s)
}
if err != nil {
s.loggerSendReadErr("connection.read.fail", err)
return
}
}
}
// send buffer
func (s *Session) send(buf []byte) error {
var err = s.conn.SetWriteDeadline(time.Now().Add(s.b.writeTimeout))
if err != nil {
s.b.Logger().Error("set.write.conn.deadline", zap.Error(err), s.RemoteZap())
return err
}
_, err = s.conn.Write(buf)
return err
}
// quit :
func (s *Session) quit() {
s.exitOnce.Do(func() {
if s.rh != nil {
s.rh.OnExit(s)
} else {
s.b.rh.OnExit(s)
}
s.b.count.Dec()
s.sendQ.Close()
if s.conn != nil {
var err = s.conn.Close()
if err != nil {
s.b.Logger().Error("close.conn", zap.Error(err), s.RemoteZap())
}
}
})
}
// recovery :
func (s *Session) recovery() {
var r = recover()
if r != nil {
//has panic
s.b.Logger().Error("session.panic", zap.Any("panic", r),
zap.Stack("stack"))
}
}
// log send/read error
func (s *Session) loggerSendReadErr(msg string, err error) {
if s.b.Logger().Level() <= zapcore.WarnLevel {
s.b.Logger().Warn(msg, s.KeyZaps(zap.Error(err), s.RemoteZap())...)
}
}
// abs remote address
func absRemoteAddr(rdAddr atomic.String, conn net.Conn) string {
var rd = rdAddr.Load()
if rd == "" {
if conn == nil {
return ""
}
var ra = conn.RemoteAddr()
if ra == nil {
return ""
}
return ra.String()
}
return rd
}
// abs session info to debug info
func absSessionInfo(value atomic.Value, ext ...zap.Field) []zap.Field {
var info = value.Load()
if info == nil {
return ext
}
var sessInfo, ok = info.(IKeyZap)
if ok {
if sessInfo == nil {
return ext
}
return sessInfo.KeyZaps(ext...)
} else {
var l = len(ext)
var c = make([]zap.Field, l+1)
c[0] = zap.Any("unknown.sessionInfo", info)
copy(c[1:], ext)
return c
}
}