-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbucket.go
283 lines (258 loc) · 6.44 KB
/
bucket.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
/*
* Copyright 2022 steven
* 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 sim
import (
"context"
"github.com/pkg/errors"
"go.uber.org/zap"
"strconv"
"sync"
"time"
"github.com/mongofs/sim/pkg/conn"
"github.com/mongofs/sim/pkg/logging"
"go.uber.org/atomic"
)
type bucketInterface interface {
// you can register the user to the bucket set
Register(client conn.Connect) (string, int64, error)
// you can offline the user in anytime
Offline(identification string)
// send message to users , if empty of users set ,will send message to all users
SendMessage(message []byte, users ...string /* if no param , it will use broadcast */)
// return the signal channel , you can use the channel to notify the bucket
// uses is offline , and delete the users' identification
SignalChannel() chan<- string
// get the number of online user
Count() int
}
type bucketMessage struct {
origin *[]byte
users *[]string
}
type bucket struct {
id string
// Attention:
// this is a switch to control bucket use channel buffer or not ,
// more higher performance you can turn it on ,if you want do message ack ,
// the better choice is turn it off
bucketChannel chan *bucketMessage
rw sync.RWMutex
// Element Number
np atomic.Int64
// users set
users map[string]conn.Connect
// Here is different point you need pay attention
// the close signal received by component that is connection
// so we need use channel to inform bucket that user is out of line
closeSig chan string
ctx context.Context
callback func()
opts *Options
}
func NewBucket(option *Options, id int ,ctx context.Context) *bucket {
res := &bucket{
id: "bucket_" + strconv.Itoa(id),
rw: sync.RWMutex{},
np: atomic.Int64{},
closeSig: make(chan string),
opts: option,
ctx: ctx,
}
res.users = make(map[string]conn.Connect, res.opts.BucketSize)
if option.BucketBuffer <= 0 {
go res.monitorDelChannel()
go res.keepAlive()
return res
} else {
res.bucketChannel = make(chan *bucketMessage, option.BucketBuffer)
res.consumer(1 << 2)
go res.monitorDelChannel()
go res.keepAlive()
return res
}
return res
}
// consumer is a goroutine pool to send message parallelly
func (h *bucket) consumer(counter int) {
for i := 0; i < counter; i++ {
go func() {
defer func() {
if err := recover(); err != nil {
logging.Log.Error("consumer", zap.Any("PANIC", err))
}
}()
for {
select {
case message := <-h.bucketChannel:
BoardCast := len(*message.users)-1 >= 0
if !BoardCast {
h.broadCast(*message.origin, false)
} else {
for _, user := range *message.users {
h.send(*message.origin, user, false)
}
}
case <-h.ctx.Done():
return
}
}
}()
}
}
func (h *bucket) Offline(identification string) {
h.rw.Lock()
cli, ok := h.users[identification]
delete(h.users, identification)
h.rw.Unlock()
if ok {
h.opts.Offline(cli, OfflineBySqueezeOut)
time.Sleep(50 * time.Millisecond)
cli.Close("Use the Bucket API : Offline ")
}
}
func (h *bucket) Register(cli conn.Connect) (string, int64, error) {
if cli == nil {
return "", 0, errors.New("sim : the obj of cli is nil ")
}
h.rw.Lock()
defer h.rw.Unlock()
h.users[cli.Identification()] = cli
h.np.Add(1)
return h.id, h.np.Load(), nil
}
func (h *bucket) SendMessage(message []byte, users ...string /* if no param , it will use broadcast */) {
if h.bucketChannel != nil {
if len(users)-1 >= 0 {
h.bucketChannel <- &bucketMessage{
origin: &message,
users: &users,
}
} else {
h.bucketChannel <- &bucketMessage{
origin: &message,
users: &users,
}
}
return
}
if len(users)-1 >= 0 {
for _, user := range users {
h.send(message, user, false)
}
return
}
h.broadCast(message, false)
}
func (h *bucket) SignalChannel() chan<- string {
return h.closeSig
}
func (h *bucket) Count() int {
h.rw.RLock()
defer h.rw.RUnlock()
return len(h.users)
}
// this function need a lot of logs
func (h *bucket) send(data []byte, token string, Ack bool) {
h.rw.RLock()
cli, ok := h.users[token]
h.rw.RUnlock()
if !ok { // user is not online
return
} else {
err := cli.Send(data)
logging.Log.Error("bucket send", zap.String("ID",cli.Identification()),zap.Error(err))
}
return
}
func (h *bucket) broadCast(data []byte, Ack bool) {
h.rw.RLock()
for _, cli := range h.users {
err := cli.Send(data)
if err != nil {
if !errors.Is(err,conn.ErrConnectionIsClosed) {
// if err == errConnectionIsClosed ,there is no need to record
logging.Log.Error("bucket broadCast", zap.String("ID",cli.Identification()),zap.Error(err))
}
continue
}
}
h.rw.RUnlock()
}
func (h *bucket) delUser(identification string) {
h.rw.Lock()
defer h.rw.Unlock()
_, ok := h.users[identification]
if !ok {
return
}
delete(h.users, identification)
//更新在线用户数量
h.np.Add(-1)
if h.callback != nil {
h.callback()
}
}
// To monitor the whole bucket
// run in a goroutine
func (h *bucket) monitorDelChannel() {
defer func() {
if err := recover(); err != nil {
logging.Log.Fatal("monitorDelChannel", zap.Any("PANIC", err))
}
}()
if h.ctx != nil {
for {
select {
case token := <-h.closeSig:
h.delUser(token)
case <-h.ctx.Done():
return
}
}
}
for {
select {
case token := <-h.closeSig:
h.delUser(token)
}
}
}
// To keepAlive the whole bucket
// run in a goroutine
func (h *bucket) keepAlive() {
defer func() {
if err := recover(); err != nil {
logging.Log.Error("keepAlive", zap.Any("PANIC", err))
}
}()
if h.opts.ClientHeartBeatInterval == 0 {
return
}
for {
var cancelCli []conn.Connect
now := time.Now().Unix()
h.rw.Lock()
for _, cli := range h.users {
inter := now - cli.GetLastHeartBeatTime()
if inter < 2*int64(h.opts.ClientHeartBeatInterval) {
continue
}
cancelCli = append(cancelCli, cli)
}
h.rw.Unlock()
for _, cancel := range cancelCli {
cancel.Close("heartbeat is not arrive ")
}
time.Sleep(10 * time.Second)
}
}