-
Notifications
You must be signed in to change notification settings - Fork 194
/
connection.go
339 lines (292 loc) · 7.12 KB
/
connection.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
// +build !windows
package gev
import (
"errors"
"fmt"
"net"
"strconv"
at "sync/atomic"
"time"
"github.com/Allenxuxu/gev/eventloop"
"github.com/Allenxuxu/gev/log"
"github.com/Allenxuxu/gev/poller"
"github.com/Allenxuxu/ringbuffer"
"github.com/Allenxuxu/toolkit/sync/atomic"
"github.com/RussellLuo/timingwheel"
"golang.org/x/sys/unix"
)
type CallBack interface {
OnMessage(c *Connection, ctx interface{}, data []byte) interface{}
OnClose(c *Connection)
}
// Connection TCP 连接
type Connection struct {
outBufferLen atomic.Int64
inBufferLen atomic.Int64
activeTime atomic.Int64
fd int
connected atomic.Bool
buffer *ringbuffer.RingBuffer
outBuffer *ringbuffer.RingBuffer // write buffer
inBuffer *ringbuffer.RingBuffer // read buffer
callBack CallBack
loop *eventloop.EventLoop
peerAddr string
ctx interface{}
KeyValueContext
idleTime time.Duration
timingWheel *timingwheel.TimingWheel
timer at.Value
protocol Protocol
}
var ErrConnectionClosed = errors.New("connection closed")
// NewConnection 创建 Connection
func NewConnection(fd int,
loop *eventloop.EventLoop,
sa unix.Sockaddr,
protocol Protocol,
tw *timingwheel.TimingWheel,
idleTime time.Duration,
callBack CallBack) *Connection {
conn := &Connection{
fd: fd,
peerAddr: sockAddrToString(sa),
outBuffer: ringbuffer.GetFromPool(),
inBuffer: ringbuffer.GetFromPool(),
callBack: callBack,
loop: loop,
idleTime: idleTime,
timingWheel: tw,
protocol: protocol,
buffer: ringbuffer.New(0),
}
conn.connected.Set(true)
if conn.idleTime > 0 {
_ = conn.activeTime.Swap(time.Now().Unix())
timer := conn.timingWheel.AfterFunc(conn.idleTime, conn.closeTimeoutConn())
conn.timer.Store(timer)
}
return conn
}
func (c *Connection) UserBuffer() *[]byte {
return c.loop.UserBuffer
}
func (c *Connection) closeTimeoutConn() func() {
return func() {
now := time.Now()
intervals := now.Sub(time.Unix(c.activeTime.Get(), 0))
if intervals >= c.idleTime {
_ = c.Close()
} else {
if c.connected.Get() {
timer := c.timingWheel.AfterFunc(c.idleTime-intervals, c.closeTimeoutConn())
c.timer.Store(timer)
}
}
}
}
// Context 获取 Context
func (c *Connection) Context() interface{} {
return c.ctx
}
// SetContext 设置 Context
func (c *Connection) SetContext(ctx interface{}) {
c.ctx = ctx
}
// PeerAddr 获取客户端地址信息
func (c *Connection) PeerAddr() string {
return c.peerAddr
}
// Connected 是否已连接
func (c *Connection) Connected() bool {
return c.connected.Get()
}
// Send 用来在非 loop 协程发送
func (c *Connection) Send(data interface{}, opts ...ConnectionOption) error {
if !c.connected.Get() {
return ErrConnectionClosed
}
opt := ConnectionOptions{}
for _, o := range opts {
o(&opt)
}
c.loop.QueueInLoop(func() {
if c.connected.Get() {
c.sendInLoop(c.protocol.Packet(c, data))
if opt.sendInLoopFinish != nil {
opt.sendInLoopFinish(data)
}
}
})
return nil
}
// Close 关闭连接
func (c *Connection) Close() error {
if !c.connected.Get() {
return ErrConnectionClosed
}
c.loop.QueueInLoop(func() {
c.handleClose(c.fd)
})
return nil
}
// ShutdownWrite 关闭可写端,等待读取完接收缓冲区所有数据
func (c *Connection) ShutdownWrite() error {
return unix.Shutdown(c.fd, unix.SHUT_WR)
}
// ReadBufferLength read buffer 当前积压的数据长度
func (c *Connection) ReadBufferLength() int64 {
return c.inBufferLen.Get()
}
// WriteBufferLength write buffer 当前积压的数据长度
func (c *Connection) WriteBufferLength() int64 {
return c.outBufferLen.Get()
}
// HandleEvent 内部使用,event loop 回调
func (c *Connection) HandleEvent(fd int, events poller.Event) {
if c.idleTime > 0 {
_ = c.activeTime.Swap(time.Now().Unix())
}
if events&poller.EventErr != 0 {
c.handleClose(fd)
return
}
if !c.outBuffer.IsEmpty() {
if events&poller.EventWrite != 0 {
// if return true, it means closed
if c.handleWrite(fd) {
return
}
if c.outBuffer.IsEmpty() {
c.outBuffer.Reset()
}
}
} else if events&poller.EventRead != 0 {
// if return true, it means closed
if c.handleRead(fd) {
return
}
if c.inBuffer.IsEmpty() {
c.inBuffer.Reset()
}
}
c.inBufferLen.Swap(int64(c.inBuffer.Length()))
c.outBufferLen.Swap(int64(c.outBuffer.Length()))
}
func (c *Connection) handlerProtocol(tmpBuffer *[]byte, buffer *ringbuffer.RingBuffer) {
ctx, receivedData := c.protocol.UnPacket(c, buffer)
for ctx != nil || len(receivedData) != 0 {
sendData := c.callBack.OnMessage(c, ctx, receivedData)
if sendData != nil {
*tmpBuffer = append(*tmpBuffer, c.protocol.Packet(c, sendData)...)
}
ctx, receivedData = c.protocol.UnPacket(c, buffer)
}
}
func (c *Connection) handleRead(fd int) (closed bool) {
// TODO 避免这次内存拷贝
buf := c.loop.PacketBuf()
n, err := unix.Read(c.fd, buf)
if n == 0 || err != nil {
if err != unix.EAGAIN {
c.handleClose(fd)
closed = true
}
return
}
if c.inBuffer.IsEmpty() {
c.buffer.WithData(buf[:n])
buf = buf[n:n]
c.handlerProtocol(&buf, c.buffer)
if !c.buffer.IsEmpty() {
first, _ := c.buffer.PeekAll()
_, _ = c.inBuffer.Write(first)
}
} else {
_, _ = c.inBuffer.Write(buf[:n])
buf = buf[:0]
c.handlerProtocol(&buf, c.inBuffer)
}
if len(buf) != 0 {
closed = c.sendInLoop(buf)
}
return
}
func (c *Connection) handleWrite(fd int) (closed bool) {
first, end := c.outBuffer.PeekAll()
n, err := unix.Write(c.fd, first)
if err != nil {
if err == unix.EAGAIN {
return
}
c.handleClose(fd)
closed = true
return
}
c.outBuffer.Retrieve(n)
if n == len(first) && len(end) > 0 {
n, err = unix.Write(c.fd, end)
if err != nil {
if err == unix.EAGAIN {
return
}
c.handleClose(fd)
closed = true
return
}
c.outBuffer.Retrieve(n)
}
if c.outBuffer.IsEmpty() {
if err := c.loop.EnableRead(fd); err != nil {
log.Error("[enableRead]", err)
}
}
return
}
func (c *Connection) handleClose(fd int) {
if c.connected.Get() {
c.connected.Set(false)
c.loop.DeleteFdInLoop(fd)
c.callBack.OnClose(c)
if err := unix.Close(fd); err != nil {
log.Error("[close fd]", err)
}
ringbuffer.PutInPool(c.inBuffer)
ringbuffer.PutInPool(c.outBuffer)
if v := c.timer.Load(); v != nil {
timer := v.(*timingwheel.Timer)
timer.Stop()
}
}
}
func (c *Connection) sendInLoop(data []byte) (closed bool) {
if !c.outBuffer.IsEmpty() {
_, _ = c.outBuffer.Write(data)
} else {
n, err := unix.Write(c.fd, data)
if err != nil && err != unix.EAGAIN {
c.handleClose(c.fd)
closed = true
return
}
if n <= 0 {
_, _ = c.outBuffer.Write(data)
} else if n < len(data) {
_, _ = c.outBuffer.Write(data[n:])
}
if !c.outBuffer.IsEmpty() {
_ = c.loop.EnableReadWrite(c.fd)
}
}
return
}
func sockAddrToString(sa unix.Sockaddr) string {
switch sa := (sa).(type) {
case *unix.SockaddrInet4:
return net.JoinHostPort(net.IP(sa.Addr[:]).String(), strconv.Itoa(sa.Port))
case *unix.SockaddrInet6:
return net.JoinHostPort(net.IP(sa.Addr[:]).String(), strconv.Itoa(sa.Port))
default:
return fmt.Sprintf("(unknown - %T)", sa)
}
}