This repository has been archived by the owner on Nov 5, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
conn_ws.go
317 lines (268 loc) · 7.04 KB
/
conn_ws.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
//go:build !windows && !appengine
// +build !windows,!appengine
package tcpGateway
import (
"encoding/binary"
"sync"
"time"
"github.com/allegro/bigcache/v2"
"github.com/gobwas/ws"
"github.com/mailru/easygo/netpoll"
wsutil "github.com/ronaksoft/rony/internal/gateway/tcp/util"
"github.com/ronaksoft/rony/internal/metrics"
"github.com/ronaksoft/rony/log"
"github.com/ronaksoft/rony/pools"
"github.com/ronaksoft/rony/tools"
"go.uber.org/zap"
"net"
"sync/atomic"
)
/*
Creation Time: 2019 - Feb - 28
Created by: (ehsan)
Maintainers:
1. Ehsan N. Moosa (E2)
Auditor: Ehsan N. Moosa (E2)
Copyright Ronak Software Group 2020
*/
// websocketConn
type websocketConn struct {
mtx sync.Mutex
connID uint64
clientIP []byte
// KV Store
kvLock tools.SpinLock
kv map[string]interface{}
// Internals
gateway *Gateway
lastActivity int64
conn net.Conn
desc *netpoll.Desc
closed bool
startTime int64
}
func newWebsocketConn(g *Gateway, conn net.Conn, clientIP []byte) (*websocketConn, error) {
desc, err := netpoll.Handle(conn,
netpoll.EventRead|netpoll.EventHup|netpoll.EventOneShot,
)
if err != nil {
return nil, err
}
// Increment total connection counter and connection ID
totalConns := atomic.AddInt32(&g.connsTotal, 1)
connID := atomic.AddUint64(&g.connsLastID, 1)
wsConn := &websocketConn{
connID: connID,
gateway: g,
conn: conn,
desc: desc,
closed: false,
kv: make(map[string]interface{}, 4),
lastActivity: tools.CPUTicks(),
}
wsConn.SetClientIP(clientIP)
g.connsMtx.Lock()
g.conns[connID] = wsConn
g.connsMtx.Unlock()
if ce := g.cfg.Logger.Check(log.DebugLevel, "Websocket Connection Created"); ce != nil {
ce.Write(
zap.Uint64("ConnID", connID),
zap.String("IP", wsConn.ClientIP()),
zap.Int32("Total", totalConns),
)
}
g.connGC.monitorConnection(connID)
return wsConn, nil
}
func (wc *websocketConn) registerDesc() error {
atomic.StoreInt64(&wc.startTime, tools.CPUTicks())
err := wc.gateway.poller.Start(wc.desc, wc.startEvent)
if err != nil {
wc.release(1)
}
return err
}
func (wc *websocketConn) release(reason int) {
// delete the reference from the gateway's conns
g := wc.gateway
g.connsMtx.Lock()
_, ok := g.conns[wc.connID]
if !ok {
g.connsMtx.Unlock()
return
}
delete(g.conns, wc.connID)
g.connsMtx.Unlock()
// Decrease the total connection counter
totalConns := atomic.AddInt32(&g.connsTotal, -1)
// fmt.Println("Conn(", wc.connID, "): LifeTime:", time.Duration(tools.CPUTicks()-atomic.LoadInt64(&wc.startTime)))
if ce := g.cfg.Logger.Check(log.DebugLevel, "Websocket Connection Removed"); ce != nil {
ce.Write(
zap.Uint64("ConnID", wc.connID),
zap.Int32("Total", totalConns),
)
}
wc.mtx.Lock()
if wc.desc != nil {
_ = g.poller.Stop(wc.desc)
_ = wc.desc.Close()
}
_ = wc.conn.Close()
if !wc.closed {
g.CloseHandler(wc)
wc.closed = true
wc.conn = nil
}
wc.mtx.Unlock()
}
func (wc *websocketConn) startEvent(event netpoll.Event) {
if atomic.LoadInt32(&wc.gateway.stop) == 1 {
return
}
if event&netpoll.EventReadHup != 0 {
wc.release(2)
return
}
if event&netpoll.EventRead != 0 {
atomic.StoreInt64(&wc.lastActivity, tools.CPUTicks())
wc.gateway.waitGroupReaders.Add(1)
err := goPoolNB.Submit(func() {
ms := acquireWebsocketMessage()
waitGroup := pools.AcquireWaitGroup()
err := wc.gateway.websocketReadPump(wc, waitGroup, *ms)
if err != nil {
wc.release(3)
} else {
_ = wc.gateway.poller.Resume(wc.desc)
}
waitGroup.Wait()
pools.ReleaseWaitGroup(waitGroup)
releaseWebsocketMessage(ms)
wc.gateway.waitGroupReaders.Done()
})
if err != nil {
wc.gateway.cfg.Logger.Warn("Error On StartEvent (Pool)", zap.Error(err))
}
}
}
func (wc *websocketConn) read(ms []wsutil.Message) ([]wsutil.Message, error) {
var err error
wc.mtx.Lock()
if wc.conn != nil {
_ = wc.conn.SetReadDeadline(time.Now().Add(defaultReadTimout))
ms, err = wsutil.ReadMessage(wc.conn, ws.StateServerSide, ms)
} else {
err = ErrConnectionClosed
}
wc.mtx.Unlock()
return ms, err
}
func (wc *websocketConn) write(opCode ws.OpCode, payload []byte) (err error) {
wc.mtx.Lock()
if wc.conn != nil {
_ = wc.conn.SetWriteDeadline(time.Now().Add(defaultWriteTimeout))
err = wsutil.WriteMessage(wc.conn, ws.StateServerSide, opCode, payload)
} else {
err = ErrWriteToClosedConn
}
wc.mtx.Unlock()
return
}
func (wc *websocketConn) Get(key string) interface{} {
wc.kvLock.Lock()
v := wc.kv[key]
wc.kvLock.Unlock()
return v
}
func (wc *websocketConn) Set(key string, val interface{}) {
wc.kvLock.Lock()
wc.kv[key] = val
wc.kvLock.Unlock()
}
func (wc *websocketConn) ConnID() uint64 {
return atomic.LoadUint64(&wc.connID)
}
func (wc *websocketConn) ClientIP() string {
return string(wc.clientIP)
}
func (wc *websocketConn) SetClientIP(ip []byte) {
wc.clientIP = append(wc.clientIP[:0], ip...)
}
// WriteBinary
// Make sure you don't use payload after calling this function, because its underlying
// array will be put back into the pool to be reused.
func (wc *websocketConn) WriteBinary(streamID int64, payload []byte) error {
if wc == nil || wc.closed {
return ErrWriteToClosedConn
}
wc.gateway.waitGroupWriters.Add(1)
wr := acquireWriteRequest(wc, ws.OpBinary)
wr.CopyPayload(payload)
err := wc.gateway.websocketWritePump(wr)
if err != nil {
wc.release(4)
}
releaseWriteRequest(wr)
metrics.IncCounter(metrics.CntGatewayOutgoingWebsocketMessage)
return nil
}
func (wc *websocketConn) Disconnect() {
wc.release(5)
}
func (wc *websocketConn) Persistent() bool {
return true
}
// writeRequest
type writeRequest struct {
wc *websocketConn
opCode ws.OpCode
payload []byte
}
func (wr *writeRequest) CopyPayload(p []byte) {
wr.payload = append(wr.payload[:0], p...)
}
// websocketConnGC the garbage collector of the stalled websocket connections
type websocketConnGC struct {
bg *bigcache.BigCache
gw *Gateway
inChan chan uint64
}
func newWebsocketConnGC(gw *Gateway) *websocketConnGC {
gc := &websocketConnGC{
gw: gw,
inChan: make(chan uint64, 1000),
}
bgConf := bigcache.DefaultConfig(time.Duration(gw.maxIdleTime))
bgConf.CleanWindow = time.Second
bgConf.Verbose = false
bgConf.OnRemoveWithReason = gc.onRemove
bgConf.Shards = 128
bgConf.MaxEntrySize = 8
bgConf.MaxEntriesInWindow = 100000
gc.bg, _ = bigcache.NewBigCache(bgConf)
// background job for receiving connIDs
go func() {
b := make([]byte, 8)
for connID := range gc.inChan {
binary.BigEndian.PutUint64(b, connID)
_ = gc.bg.Set(tools.ByteToStr(b), b)
}
}()
return gc
}
func (gc *websocketConnGC) onRemove(key string, entry []byte, reason bigcache.RemoveReason) {
switch reason {
case bigcache.Expired:
connID := binary.BigEndian.Uint64(entry)
if wsConn := gc.gw.getConnection(connID); wsConn != nil {
if tools.CPUTicks()-atomic.LoadInt64(&wsConn.lastActivity) > gc.gw.maxIdleTime {
wsConn.release(6)
} else {
gc.monitorConnection(connID)
}
}
}
}
func (gc *websocketConnGC) monitorConnection(connID uint64) {
gc.inChan <- connID
}