-
Notifications
You must be signed in to change notification settings - Fork 1
/
stream.go
349 lines (327 loc) · 9.99 KB
/
stream.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
340
341
342
343
344
345
346
347
348
349
package base
import (
"github.com/tevino/abool/v2"
"github.com/tomasliu-agora/rtm2"
"go.uber.org/zap"
"sync"
)
type stream struct {
channel string
client *client
options *rtm2.StreamOptions
topicEvents chan *rtm2.TopicEvent
tc chan string
joined *abool.AtomicBool
topics sync.Map
topicSubscribes sync.Map
lg *zap.Logger
}
type streamSub struct {
mc chan *rtm2.Message
userIds sync.Map
}
func (s *stream) Join(opts ...rtm2.StreamOption) (map[string][]string, <-chan *rtm2.TopicEvent, <-chan string, error) {
s.lg.Debug("Join")
if s.joined.SetToIf(false, true) {
for _, opt := range opts {
opt(s.options)
}
s.lg.Debug("join channel", zap.String("token", s.options.Token), zap.Bool("metadata", s.options.Metadata), zap.Bool("presence", s.options.Presence), zap.Bool("lock", s.options.Lock))
req := &StreamJoinReq{Channel: s.channel, Token: s.options.Token, Metadata: s.options.Metadata, Presence: s.options.Presence, Lock: s.options.Lock}
if s.options.Metadata {
s.client.storage.subscribe(s.client.storage.unifyChannelKey(s.channel, rtm2.ChannelTypeStream))
}
if s.options.Presence {
s.client.presence.subscribe(s.client.presence.unifyChannelKey(s.channel, rtm2.ChannelTypeStream))
}
if s.options.Lock {
s.client.lock.subscribe(unify(s.channel, rtm2.ChannelTypeStream))
}
_, errCode, err := s.client.invoker.OnReceived(req)
if err != nil {
return nil, nil, nil, err
}
if err = rtm2.ErrorFromCode(errCode); err != nil {
return nil, nil, nil, err
}
snapshotEvent := <-s.topicEvents
return snapshotEvent.Snapshot, s.topicEvents, s.tc, nil
} else {
return nil, nil, nil, rtm2.ERR_ALREADY_JOIN_CHANNEL
}
}
func (s *stream) RenewToken(token string) error {
s.lg.Debug("Renew Token")
req := &RenewTokenReq{
Token: token,
Channel: s.channel,
}
_, errCode, err := s.client.invoker.OnReceived(req)
if err != nil {
return err
}
if err = rtm2.ErrorFromCode(errCode); err != nil {
return err
}
return nil
}
func (s *stream) Leave() error {
s.lg.Debug("Leave")
if s.joined.SetToIf(true, false) {
s.lg.Debug("leave channel", zap.String("token", s.options.Token), zap.Bool("metadata", s.options.Metadata), zap.Bool("presence", s.options.Presence), zap.Bool("lock", s.options.Lock))
// RTE leave channel
if s.options.Metadata {
s.client.storage.unsubscribe(s.client.storage.unifyChannelKey(s.channel, rtm2.ChannelTypeStream))
}
if s.options.Presence {
s.client.presence.unsubscribe(s.client.presence.unifyChannelKey(s.channel, rtm2.ChannelTypeStream))
}
if s.options.Lock {
s.client.lock.unsubscribe(unify(s.channel, rtm2.ChannelTypeStream))
}
req := &StreamLeaveReq{Channel: s.channel}
_, errCode, err := s.client.invoker.OnReceived(req)
if err != nil {
return err
}
if err = rtm2.ErrorFromCode(errCode); err != nil {
return err
}
s.client.streamChannels.Delete(s.channel)
return nil
} else {
return rtm2.ERR_NOT_JOIN_CHANNEL
}
}
func (s *stream) ChannelName() string {
return s.channel
}
func (s *stream) JoinTopic(topic string, opts ...rtm2.StreamOption) error {
s.lg.Debug("JoinTopic")
if s.joined.IsNotSet() {
return rtm2.ERR_NOT_JOIN_CHANNEL
}
options := &rtm2.StreamOptions{}
for _, opt := range opts {
opt(options)
}
if _, ok := s.topics.LoadOrStore(topic, true); ok {
s.lg.Error("already joined topic", zap.String("topic", topic))
return rtm2.ERR_TOPIC_ALREADY_JOINED
}
// RTE join topic
req := &StreamJoinTopicReq{Channel: s.channel, Topic: topic, Qos: int32(options.QOS), Priority: int32(options.Priority), SyncMedia: options.SyncMedia, Meta: options.Meta}
_, errCode, err := s.client.invoker.OnReceived(req)
if err != nil {
s.topics.Delete(topic)
return err
}
if err = rtm2.ErrorFromCode(errCode); err != nil {
s.topics.Delete(topic)
return err
}
return nil
}
func (s *stream) PublishTopic(topic string, message []byte, opts ...rtm2.StreamOption) error {
s.lg.Debug("PublishTopic")
if s.joined.IsNotSet() {
return rtm2.ERR_NOT_JOIN_CHANNEL
}
if _, ok := s.topics.Load(topic); ok {
options := &rtm2.StreamOptions{}
for _, opt := range opts {
opt(options)
}
// RTE publish topic
req := &StreamMessageReq{Channel: s.channel, Topic: topic, Message: message, Type: int32(options.Type), SendTs: int64(options.SendTs)}
_, errCode, err := s.client.invoker.OnReceived(req)
if err != nil {
s.topics.Delete(topic)
return err
}
if err = rtm2.ErrorFromCode(errCode); err != nil {
s.topics.Delete(topic)
return err
}
return nil
} else {
s.lg.Error("topic not joined", zap.String("topic", topic))
return rtm2.ERR_PUBLISH_TOPIC_MESSAGE_FAILED
}
}
func (s *stream) LeaveTopic(topic string) error {
s.lg.Debug("LeaveTopic")
if s.joined.IsNotSet() {
return rtm2.ERR_NOT_JOIN_CHANNEL
}
if _, ok := s.topics.LoadAndDelete(topic); ok {
// RTE leave topic
req := &StreamLeaveTopicReq{Channel: s.channel, Topic: topic}
_, errCode, err := s.client.invoker.OnReceived(req)
if err != nil {
s.topics.Delete(topic)
return err
}
if err = rtm2.ErrorFromCode(errCode); err != nil {
s.topics.Delete(topic)
return err
}
return nil
} else {
s.lg.Warn("topic not joined", zap.String("topic", topic))
return nil
}
}
func (s *stream) SubscribeTopic(topic string, userIds []string) (<-chan *rtm2.Message, error) {
s.lg.Debug("SubscribeTopic")
if s.joined.IsNotSet() {
return nil, rtm2.ERR_NOT_JOIN_CHANNEL
}
sub := &streamSub{mc: make(chan *rtm2.Message, defaultChanSize)}
for _, userId := range userIds {
sub.userIds.Store(userId, true)
}
users := make([]string, 0)
if value, ok := s.topicSubscribes.LoadOrStore(topic, sub); ok {
sub = value.(*streamSub)
if len(userIds) > 0 {
for _, userId := range userIds {
if _, ok := sub.userIds.LoadOrStore(userId, true); !ok {
users = append(users, userId)
}
}
}
s.lg.Debug("New user subscribed in topic", zap.String("topic", topic), zap.Strings("userIds", userIds))
} else {
users = userIds
s.lg.Debug("New topic subscribed", zap.String("topic", topic), zap.Strings("userIds", userIds))
}
if len(users) > 0 || len(userIds) == 0 {
// RTE sub topic
req := &StreamSubTopicReq{Channel: s.channel, Topic: topic, UserIds: userIds}
resp, errCode, err := s.client.invoker.OnReceived(req)
if err != nil {
return nil, err
}
if err = rtm2.ErrorFromCode(errCode); err != nil {
return nil, err
}
subResp := resp.(*StreamSubTopicResp)
s.lg.Info("sub resp on topic", zap.String("topic", topic), zap.Strings("succeed", subResp.Succeed), zap.Strings("failed", subResp.Failed))
return sub.mc, nil
} else {
s.lg.Debug("No need to send request", zap.String("topic", topic), zap.Strings("userIds", userIds))
return sub.mc, nil
}
}
func (s *stream) UnsubscribeTopic(topic string, userIds []string) error {
s.lg.Debug("UnsubscribeTopic")
if s.joined.IsNotSet() {
return rtm2.ERR_NOT_JOIN_CHANNEL
}
users := make([]string, 0)
if len(userIds) > 0 {
if value, ok := s.topicSubscribes.Load(topic); ok {
sub := value.(*streamSub)
for _, userId := range userIds {
if _, ok := sub.userIds.LoadAndDelete(userId); ok {
users = append(users, userId)
}
}
count := 0
sub.userIds.Range(func(key, value interface{}) bool {
count += 1
return true
})
/*
if count == 0 {
s.topicSubscribes.Delete(topic)
close(sub.mc)
s.lg.Debug("topic not interested", zap.String("topic", topic), zap.Strings("userIds", userIds))
}
*/
s.lg.Debug("user unsubscribed in topic", zap.String("topic", topic), zap.Strings("userIds", userIds))
} else {
s.lg.Warn("Topic not subscribed", zap.String("topic", topic), zap.Strings("userIds", userIds))
return nil
}
}
if len(users) > 0 || len(userIds) == 0 {
// RTE sub topic
req := &StreamUnsubTopicReq{Channel: s.channel, Topic: topic, UserIds: userIds}
_, errCode, err := s.client.invoker.OnReceived(req)
if err != nil {
return err
}
if err = rtm2.ErrorFromCode(errCode); err != nil {
return err
}
} else {
s.lg.Debug("No need to send request", zap.String("topic", topic), zap.Strings("userIds", userIds))
}
/*
else {
if value, ok := s.topicSubscribes.LoadAndDelete(topic); ok {
sub := value.(*streamSub)
close(sub.mc)
s.lg.Debug("topic not interested", zap.String("topic", topic), zap.Strings("userIds", userIds))
}
}
*/
return nil
}
func (s *stream) GetSubscribedUsers(topic string) ([]string, error) {
s.lg.Debug("GetSubscribedUsers")
if _, ok := s.topicSubscribes.Load(topic); ok {
req := &StreamSubListReq{Channel: s.channel, Topic: topic}
resp, errCode, err := s.client.invoker.OnReceived(req)
if err != nil {
s.topics.Delete(topic)
return nil, err
}
if err = rtm2.ErrorFromCode(errCode); err != nil {
s.topics.Delete(topic)
return nil, err
}
subResp := resp.(*StreamSubListResp)
return subResp.UserIds, nil
}
return nil, rtm2.ERR_NOT_SUBSCRIBED
}
func (s *stream) OnMessage(msg *StreamMessageEvent) {
m := &rtm2.Message{UserId: msg.Publisher, Type: rtm2.MessageType(msg.Type), Message: msg.Message}
if value, ok := s.topicSubscribes.Load(msg.Topic); ok {
ssub := value.(*streamSub)
if _, exists := ssub.userIds.Load(msg.Publisher); exists {
ssub.mc <- m
s.lg.Debug("message", zap.String("topic", msg.Topic), zap.String("publisher", msg.Publisher), zap.Int("message", len(msg.Message)))
}
}
}
func (e *StreamTopicEvent) toRTM2Event() *rtm2.TopicEvent {
rst := &rtm2.TopicEvent{}
rst.Channel = e.Channel
rst.Type = rtm2.TopicEventType(e.Type)
rst.UserId = e.UserId
switch rst.Type {
case rtm2.TopicEventSnapshot:
rst.Snapshot = make(map[string][]string)
for _, info := range e.Infos {
var ps []string
for _, p := range info.Publishers {
ps = append(ps, p.UserId)
}
rst.Snapshot[info.Topic] = ps
}
case rtm2.TopicEventJoin, rtm2.TopicEventLeave:
if len(e.Infos) != 0 {
rst.Topic = e.Infos[0].Topic
rst.UserId = e.Infos[0].Publishers[0].UserId
}
}
return rst
}
func (s *stream) OnTopicEvent(event *StreamTopicEvent) {
s.lg.Debug("on topic event", zap.Any("event", event))
s.topicEvents <- event.toRTM2Event()
}