-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
messaging.go
645 lines (572 loc) · 14.6 KB
/
messaging.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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
package wfb
import (
"encoding/json"
"fmt"
"strings"
"firebase.google.com/go/messaging"
"github.com/wasabee-project/Wasabee-Server/config"
"github.com/wasabee-project/Wasabee-Server/log"
wm "github.com/wasabee-project/Wasabee-Server/messaging"
"github.com/wasabee-project/Wasabee-Server/model"
)
// AgentLocation alerts all appropriate teams about an agent's moving
// Do not send to topic since this hits the fanout-quota quickly
// We do the fanout manually, sending directly to tokens has a much higher quota
func AgentLocation(gid model.GoogleID) {
if !config.IsFirebaseRunning() {
return
}
if !ratelimitAgent(gid) {
// log.Debugw("skipping agent due to rate limits", "gid", gid)
return
}
tokens, err := gid.FirebaseLocationTokens()
if len(tokens) == 0 {
return
}
var toSend []*messaging.Message
var brTokens []string
var curTeam model.TeamID
var skipping bool
for _, token := range tokens {
if curTeam != token.TeamID {
curTeam = token.TeamID
skipping = false
if !ratelimitTeam(token.TeamID) {
log.Debugw("skipping this team due to rate limits", "teamID", token.TeamID)
skipping = true
continue
}
}
if skipping {
continue
}
// not doing multicast due to multiple shared teams
m := messaging.Message{
Token: token.Token,
Data: map[string]string{
"msg": string(token.TeamID),
"cmd": "Agent Location Change",
"srv": config.Get().HTTP.Webroot,
},
}
toSend = append(toSend, &m)
brTokens = append(brTokens, token.Token)
if len(toSend) > 500 {
log.Debug("more than 500 messages outgoing on AgentLocation send, only sending 500 -- FIXME scot was lazy")
break
}
}
if len(toSend) == 0 {
return
}
br, err := msg.SendAll(fbctx, toSend)
if err != nil {
log.Error(err)
return
}
processBatchResponse(br, brTokens) // do the work on an async go routine?
return
}
// AssignLink lets an agent know they have a new assignment on a given operation
func AssignLink(gid model.GoogleID, linkID model.TaskID, opID model.OperationID, updateID string) error {
if !config.IsFirebaseRunning() {
return nil
}
tokens, err := gid.GetFirebaseTokens()
if err != nil {
log.Error(err)
return err
}
if len(tokens) == 0 {
return nil
}
data := map[string]string{
"opID": string(opID),
"linkID": string(linkID),
"cmd": "Link Assignment Change",
"updateID": updateID,
}
genericMulticast(data, tokens)
return nil
}
// AssignMarker lets an gent know they have a new assignment on a given operation
func AssignMarker(gid model.GoogleID, markerID model.TaskID, opID model.OperationID, updateID string) error {
if !config.IsFirebaseRunning() {
return nil
}
tokens, err := gid.GetFirebaseTokens()
if err != nil {
log.Error(err)
return err
}
if len(tokens) == 0 {
return nil
}
data := map[string]string{
"opID": string(opID),
"markerID": string(markerID),
"cmd": "Marker Assignment Change",
"updateID": updateID,
}
genericMulticast(data, tokens)
return nil
}
// AssignTask lets an gent know they have a new assignment on a given operation
func AssignTask(gid model.GoogleID, taskID model.TaskID, opID model.OperationID, updateID string) error {
if !config.IsFirebaseRunning() {
return nil
}
tokens, err := gid.GetFirebaseTokens()
if err != nil {
log.Error(err)
return err
}
if len(tokens) == 0 {
return nil
}
data := map[string]string{
"opID": string(opID),
"taskID": string(taskID),
"cmd": "Task Assignment Change",
"updateID": updateID,
}
genericMulticast(data, tokens)
return nil
}
// MarkerStatus reports a marker update to a team/topic
func MarkerStatus(markerID model.TaskID, opID model.OperationID, teams []model.TeamID, status string, updateID string) error {
if !config.IsFirebaseRunning() {
return nil
}
if !ratelimitOp(opID) {
return nil
}
data := map[string]string{
"opID": string(opID),
"markerID": string(markerID),
"msg": status,
"cmd": "Marker Status Change",
"srv": config.Get().HTTP.Webroot,
"updateID": updateID,
}
conditions := teamsToCondition(teams)
multicastFantoutMutex.Lock()
defer multicastFantoutMutex.Unlock()
for _, condition := range conditions {
m := messaging.Message{
Condition: condition,
Data: data,
}
if _, err := msg.Send(fbctx, &m); err != nil {
log.Error(err)
if messaging.IsTooManyTopics(err) || messaging.IsMessageRateExceeded(err) {
slowdown()
}
return err
}
}
return nil
}
// LinkStatus reports a link update to a team/topic
func LinkStatus(linkID model.TaskID, opID model.OperationID, teams []model.TeamID, status string, updateID string) error {
if !config.IsFirebaseRunning() {
return nil
}
if !ratelimitOp(opID) {
return nil
}
data := map[string]string{
"opID": string(opID),
"linkID": string(linkID),
"msg": status,
"cmd": "Link Status Change",
"srv": config.Get().HTTP.Webroot,
"updateID": updateID,
}
conditions := teamsToCondition(teams)
multicastFantoutMutex.Lock()
defer multicastFantoutMutex.Unlock()
for _, condition := range conditions {
m := messaging.Message{
Condition: condition,
Data: data,
}
if _, err := msg.Send(fbctx, &m); err != nil {
log.Error(err)
if messaging.IsTooManyTopics(err) || messaging.IsMessageRateExceeded(err) {
slowdown()
}
return err
}
}
return nil
}
// TaskStatus reports a task update to a team/topic
func TaskStatus(taskID model.TaskID, opID model.OperationID, teams []model.TeamID, status string, updateID string) error {
if !config.IsFirebaseRunning() {
return nil
}
if !ratelimitOp(opID) {
return nil
}
data := map[string]string{
"opID": string(opID),
"taskID": string(taskID),
"msg": status,
"cmd": "Task Status Change",
"srv": config.Get().HTTP.Webroot,
"updateID": updateID,
}
conditions := teamsToCondition(teams)
multicastFantoutMutex.Lock()
defer multicastFantoutMutex.Unlock()
for _, condition := range conditions {
m := messaging.Message{
Condition: condition,
Data: data,
}
if _, err := msg.Send(fbctx, &m); err != nil {
log.Error(err)
if messaging.IsTooManyTopics(err) || messaging.IsMessageRateExceeded(err) {
slowdown()
}
return err
}
}
return nil
}
// addToRemote subscribes all tokens for a given agent to a team/topic
func addToRemote(g wm.GoogleID, teamID wm.TeamID) error {
if !config.IsFirebaseRunning() {
return nil
}
gid := model.GoogleID(g)
tokens, err := gid.GetFirebaseTokens()
if err != nil {
log.Error(err)
return err
}
if len(tokens) == 0 {
return nil
}
tmr, err := msg.SubscribeToTopic(fbctx, tokens, string(teamID))
if err != nil {
log.Error(err)
return err
}
if tmr != nil && tmr.FailureCount > 0 {
for _, f := range tmr.Errors {
_ = model.RemoveFirebaseToken(tokens[f.Index])
}
}
return nil
}
// removeFromRemote removes an agent's subscriptions to a given topic/team
func removeFromRemote(g wm.GoogleID, teamID wm.TeamID) error {
if !config.IsFirebaseRunning() {
return nil
}
gid := model.GoogleID(g)
tokens, err := gid.GetFirebaseTokens()
if err != nil {
log.Error(err)
return err
}
if len(tokens) == 0 {
return nil
}
tmr, err := msg.UnsubscribeFromTopic(fbctx, tokens, string(teamID))
if err != nil {
log.Error(err)
return err
}
if tmr != nil && tmr.FailureCount > 0 {
for _, f := range tmr.Errors {
_ = model.RemoveFirebaseToken(tokens[f.Index])
}
}
return nil
}
// sendMessage is registered with Wasabee for sending messages
func sendMessage(g wm.GoogleID, message string) (bool, error) {
if !config.IsFirebaseRunning() {
return false, nil
}
gid := model.GoogleID(g)
tokens, err := gid.GetFirebaseTokens()
if err != nil {
log.Error(err)
return false, err
}
if len(tokens) == 0 {
return false, nil
}
data := map[string]string{
"msg": message,
"cmd": "Generic Message",
}
genericMulticast(data, tokens)
return true, nil
}
// sendTarget sends a portal name/guid to an agent
func sendTarget(g wm.GoogleID, t wm.Target) error {
if !config.IsFirebaseRunning() {
return nil
}
gid := model.GoogleID(g)
tokens, err := gid.GetFirebaseTokens()
if err != nil {
log.Error(err)
return err
}
if len(tokens) == 0 {
return nil
}
m, err := json.Marshal(t)
if err != nil {
log.Error(err)
return err
}
data := map[string]string{
"msg": string(m),
"cmd": "Target",
}
genericMulticast(data, tokens)
return nil
}
// MapChange alerts teams of the need to need to refresh map data
func MapChange(teams []model.TeamID, opID model.OperationID, updateID string) error {
if !config.IsFirebaseRunning() {
return nil
}
if !ratelimitOp(opID) {
return nil
}
data := map[string]string{
"opID": string(opID),
"updateID": updateID,
"cmd": "Map Change",
"srv": config.Get().HTTP.Webroot,
}
conditions := teamsToCondition(teams)
multicastFantoutMutex.Lock()
defer multicastFantoutMutex.Unlock()
for _, condition := range conditions {
m := messaging.Message{
Condition: condition,
Data: data,
}
if _, err := msg.Send(fbctx, &m); err != nil {
log.Error(err)
if messaging.IsTooManyTopics(err) || messaging.IsMessageRateExceeded(err) {
slowdown()
}
return err
}
}
return nil
}
// AgentLogin alerts a team of an agent on that team logging in
func AgentLogin(teams []model.TeamID, gid model.GoogleID) error {
if !config.IsFirebaseRunning() {
return nil
}
data := map[string]string{
"gid": string(gid),
"cmd": "Login",
"srv": config.Get().HTTP.Webroot,
}
conditions := teamsToCondition(teams)
multicastFantoutMutex.Lock()
defer multicastFantoutMutex.Unlock()
for _, condition := range conditions {
m := messaging.Message{
Condition: condition,
Data: data,
}
if _, err := msg.Send(fbctx, &m); err != nil {
log.Error(err)
if messaging.IsTooManyTopics(err) || messaging.IsMessageRateExceeded(err) {
slowdown()
}
return err
}
}
return nil
}
// sendAnnounce sends a generic message to a team
func sendAnnounce(teamID wm.TeamID, a wm.Announce) error {
if !config.IsFirebaseRunning() {
return nil
}
data := map[string]string{
"msg": a.Text,
"cmd": "Generic Message",
"opID": string(a.OpID),
"sender": string(a.Sender),
"srv": config.Get().HTTP.Webroot,
}
m := messaging.Message{
Topic: string(teamID),
Data: data,
}
if _, err := msg.Send(fbctx, &m); err != nil {
log.Error(err)
if messaging.IsTooManyTopics(err) || messaging.IsMessageRateExceeded(err) {
slowdown()
}
return err
}
return nil
}
// deleteOperation tells everyone (on this server) to remove a specific op
func deleteOperation(opID wm.OperationID) error {
if !config.IsFirebaseRunning() {
return nil
}
tokens, err := model.FirebaseBroadcastList()
if err != nil {
log.Error(err)
return err
}
if len(tokens) == 0 {
return nil
}
data := map[string]string{
"cmd": "Delete",
"opID": string(opID),
}
// do this in its own worker since it might take a while
go genericMulticast(data, tokens)
return nil
}
// agentDeleteOperation notifies a single agent of the need to delete an operation (e.g. when removed from a team)
func agentDeleteOperation(g wm.GoogleID, opID wm.OperationID) error {
if !config.IsFirebaseRunning() {
return nil
}
gid := model.GoogleID(g)
tokens, err := gid.GetFirebaseTokens()
if err != nil {
log.Error(err)
return err
}
if len(tokens) == 0 {
return nil
}
data := map[string]string{
"cmd": "Delete",
"opID": string(opID),
}
genericMulticast(data, tokens)
return nil
}
// genericMulticast sends multicast messages directly to agents, taking care of breaking into proper segments and cleaning up invalid tokens
func genericMulticast(data map[string]string, tokens []string) {
if len(tokens) == 0 {
return
}
data["srv"] = config.Get().HTTP.Webroot
// can send up to 500 per block
for len(tokens) > 0 {
r := len(tokens)
if r > 500 {
r = 500
}
subset := tokens[:r]
tokens = tokens[r:]
m := messaging.MulticastMessage{
Data: data,
Tokens: subset,
}
br, err := msg.SendMulticast(fbctx, &m)
if err != nil {
log.Error(err)
return // carry on ?
}
log.Debugw("multicast block", "success", br.SuccessCount, "failure", br.FailureCount)
processBatchResponse(br, subset) // spawn a go routine? would async help here?
}
}
// processBatchResponse looks for invalid tokens responses and removes the offending tokens
func processBatchResponse(br *messaging.BatchResponse, tokens []string) {
var slowed bool
for pos, resp := range br.Responses {
if !resp.Success {
if messaging.IsInternal(resp.Error) || messaging.IsUnknown(resp.Error) || messaging.IsServerUnavailable(resp.Error) {
continue
}
if messaging.IsRegistrationTokenNotRegistered(resp.Error) {
_ = model.RemoveFirebaseToken(tokens[pos])
continue
}
if messaging.IsMessageRateExceeded(resp.Error) && !slowed {
slowdown()
slowed = true // only one slowdown step per message send
continue
}
log.Infow("processBatchResponse", "error", resp.Error)
}
}
}
// Resubscribe refreshes all the topic subscriptions for every team
func Resubscribe() {
teams, err := model.GetAllTeams()
if err != nil {
log.Error(err)
return
}
for _, teamID := range teams {
tokens, err := teamID.FetchFBTokens()
if err != nil || len(tokens) == 0 {
continue
}
// TODO: fix this if we ever see it...
if len(tokens) > 1000 {
log.Warnw("team has more than 1000 tokens, only re-subscribing the first 1000", "teamID", teamID, "count", len(tokens), "scot is lazy", "AF")
tokens = tokens[:1000]
}
// log.Debugw("resubscribing tokens", "teamID", teamID, "count", len(tokens))
tmr, err := msg.SubscribeToTopic(fbctx, tokens, string(teamID))
if err != nil && !messaging.IsUnknown(err) {
log.Error(err)
return
}
if tmr != nil && tmr.FailureCount > 0 {
for _, f := range tmr.Errors {
if !strings.Contains(f.Reason, "code: internal-error") {
log.Debugw("removing dead firebase token", "token", tokens[f.Index][:24], "reason", f.Reason)
_ = model.RemoveFirebaseToken(tokens[f.Index])
} else {
log.Debugw("not removing firebase token", "reason", f.Reason)
}
}
}
}
}
func teamsToCondition(teams []model.TeamID) []string {
var conditionSet []string
if len(teams) == 0 {
return conditionSet
}
for len(teams) > 0 {
r := len(teams)
if r > 5 {
r = 5
}
subset := teams[:r]
teams = teams[r:]
var condition strings.Builder
for i, teamID := range subset {
if i > 0 {
condition.WriteString(" || ")
}
topic := fmt.Sprintf("'%s' in topics", string(teamID))
condition.WriteString(topic)
}
// log.Debug(condition.String())
conditionSet = append(conditionSet, condition.String())
}
return conditionSet
}