-
Notifications
You must be signed in to change notification settings - Fork 3
/
group.go
301 lines (251 loc) · 6.91 KB
/
group.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
package router
import (
"context"
"git.golaxy.org/core/ec"
"git.golaxy.org/core/utils/generic"
"git.golaxy.org/core/utils/uid"
"git.golaxy.org/framework/net/gtp/transport"
"git.golaxy.org/framework/plugins/log"
"git.golaxy.org/framework/utils/binaryutil"
etcdv3 "go.etcd.io/etcd/client/v3"
"path"
"slices"
"strings"
"sync"
)
// IGroup 分组接口
type IGroup interface {
context.Context
// GetAddr 获取分组地址
GetAddr() string
// Add 添加实体
Add(ctx context.Context, entIds ...uid.Id) error
// Remove 删除实体
Remove(ctx context.Context, entIds ...uid.Id) error
// Range 遍历所有实体
Range(fun generic.Func1[uid.Id, bool])
// Each 遍历所有实体
Each(fun generic.Action1[uid.Id])
// Count 获取实体数量
Count() int
// RefreshTTL 刷新TTL
RefreshTTL(ctx context.Context) error
// SendData 发送数据
SendData(data []byte) error
// SendEvent 发送自定义事件
SendEvent(event transport.IEvent) error
// SendDataChan 发送数据的channel
SendDataChan() chan<- binaryutil.RecycleBytes
// SendEventChan 发送自定义事件的channel
SendEventChan() chan<- transport.IEvent
}
type _Group struct {
sync.RWMutex
context.Context
terminate context.CancelFunc
router *_Router
groupKey string
leaseId etcdv3.LeaseID
revision int64
entities []uid.Id
sendDataChan chan binaryutil.RecycleBytes
sendEventChan chan transport.IEvent
}
// GetAddr 获取分组地址
func (g *_Group) GetAddr() string {
return strings.TrimPrefix(g.groupKey, g.router.options.GroupKeyPrefix)
}
// Add 添加实体
func (g *_Group) Add(ctx context.Context, entIds ...uid.Id) error {
if ctx == nil {
ctx = context.Background()
}
if len(entIds) <= 0 {
return nil
}
opsPut := make([]etcdv3.Op, 0, len(entIds)*2)
for _, entId := range entIds {
opsPut = append(opsPut,
etcdv3.OpPut(path.Join(g.groupKey, entId.String()), "", etcdv3.WithLease(g.leaseId)),
etcdv3.OpPut(path.Join(g.router.options.EntityGroupsKeyPrefix, entId.String(), g.GetAddr()), "", etcdv3.WithLease(g.leaseId)),
)
}
_, err := g.router.client.Txn(ctx).
Then(opsPut...).
Commit()
return err
}
// Remove 删除实体
func (g *_Group) Remove(ctx context.Context, entIds ...uid.Id) error {
if ctx == nil {
ctx = context.Background()
}
if len(entIds) <= 0 {
return nil
}
opsDel := make([]etcdv3.Op, 0, len(entIds)*2)
for _, entId := range entIds {
opsDel = append(opsDel,
etcdv3.OpDelete(path.Join(g.groupKey, entId.String())),
etcdv3.OpDelete(path.Join(g.router.options.EntityGroupsKeyPrefix, entId.String(), g.GetAddr())),
)
}
_, err := g.router.client.Txn(ctx).
Then(opsDel...).
Commit()
return err
}
// Range 遍历所有实体
func (g *_Group) Range(fun generic.Func1[uid.Id, bool]) {
g.RLock()
copied := slices.Clone(g.entities)
g.RUnlock()
for i := range copied {
if !fun.Exec(copied[i]) {
return
}
}
}
// Each 遍历所有实体
func (g *_Group) Each(fun generic.Action1[uid.Id]) {
g.RLock()
copied := slices.Clone(g.entities)
g.RUnlock()
for i := range copied {
fun.Exec(copied[i])
}
}
// Count 获取实体数量
func (g *_Group) Count() int {
g.RLock()
defer g.Unlock()
return len(g.entities)
}
// RefreshTTL 刷新TTL
func (g *_Group) RefreshTTL(ctx context.Context) error {
if ctx == nil {
ctx = context.Background()
}
_, err := g.router.client.KeepAliveOnce(ctx, g.leaseId)
return err
}
// SendData 发送数据
func (g *_Group) SendData(data []byte) error {
g.RLock()
defer g.RUnlock()
for i := range g.entities {
entId := g.entities[i]
g.router.servCtx.CallVoid(entId, func(entity ec.Entity, _ ...any) {
session, ok := g.router.LookupSession(entity.GetId())
if !ok {
return
}
err := session.SendData(data)
if err != nil {
log.Errorf(g.router.servCtx, "send data(%d) to session %q remote %q failed, %s", len(data), session.GetId(), session.GetRemoteAddr(), err)
}
})
}
return nil
}
// SendEvent 发送自定义事件
func (g *_Group) SendEvent(event transport.IEvent) error {
g.RLock()
defer g.RUnlock()
for i := range g.entities {
entId := g.entities[i]
g.router.servCtx.CallVoid(entId, func(entity ec.Entity, _ ...any) {
session, ok := g.router.LookupSession(entity.GetId())
if !ok {
return
}
err := session.SendEvent(event)
if err != nil {
log.Errorf(g.router.servCtx, "send event(%d) to session %q remote %q failed, %s", event.Msg.MsgId(), session.GetId(), session.GetRemoteAddr(), err)
}
})
}
return nil
}
// SendDataChan 发送数据的channel
func (g *_Group) SendDataChan() chan<- binaryutil.RecycleBytes {
if g.sendDataChan == nil {
log.Panicf(g.router.servCtx, "send data channel size less equal 0, can't be used")
}
return g.sendDataChan
}
// SendEventChan 发送自定义事件的channel
func (g *_Group) SendEventChan() chan<- transport.IEvent {
if g.sendEventChan == nil {
log.Panicf(g.router.servCtx, "send event channel size less equal 0, can't be used")
}
return g.sendEventChan
}
func (g *_Group) mainLoop() {
ctx, cancel := context.WithCancel(g)
if g.router.options.GroupAutoRefreshTTL {
rspChan, err := g.router.client.KeepAlive(ctx, g.leaseId)
if err != nil {
log.Errorf(g.router.servCtx, "keep alive groupKey %q lease %q failed, %s", g.groupKey, g.leaseId, err)
goto watch
}
go func() {
for range rspChan {
log.Debugf(g.router.servCtx, "refresh groupKey %q ttl success", g.groupKey)
}
}()
}
watch:
watchChan := g.router.client.Watch(ctx, g.groupKey, etcdv3.WithRev(g.revision), etcdv3.WithPrefix(), etcdv3.WithIgnoreValue())
log.Debugf(g.router.servCtx, "start watch groupKey %q", g.groupKey)
for watchRsp := range watchChan {
if watchRsp.Canceled {
log.Debugf(g.router.servCtx, "stop watch groupKey %q", g.groupKey)
goto end
}
if watchRsp.Err() != nil {
log.Errorf(g.router.servCtx, "interrupt watch groupKey %q, %s", g.groupKey, watchRsp.Err())
goto end
}
g.Lock()
for _, event := range watchRsp.Events {
switch event.Type {
case etcdv3.EventTypePut:
key := string(event.Kv.Key)
if key == g.groupKey {
continue
}
entId := uid.From(path.Base(key))
if !slices.Contains(g.entities, entId) {
g.entities = append(g.entities, entId)
}
g.router.entityGroupsCache.Del(entId, watchRsp.Header.Revision)
case etcdv3.EventTypeDelete:
key := string(event.Kv.Key)
if key == g.groupKey {
cancel()
continue
}
entId := uid.From(path.Base(key))
idx := slices.Index(g.entities, entId)
if idx >= 0 {
g.entities = slices.Delete(g.entities, idx, idx+1)
}
g.router.entityGroupsCache.Del(entId, watchRsp.Header.Revision)
default:
log.Errorf(g.router.servCtx, "unknown event type %q", event.Type)
continue
}
}
if g.revision < watchRsp.Header.Revision {
g.revision = watchRsp.Header.Revision
}
g.Unlock()
}
end:
g.RLock()
for _, entId := range g.entities {
g.router.entityGroupsCache.Del(entId, g.revision)
}
g.RUnlock()
}