forked from Dri0m/flashpoint-submission-system
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathnotificationconsumer.go
109 lines (94 loc) · 2.62 KB
/
notificationconsumer.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
package service
import (
"context"
"database/sql"
"sync"
"time"
"github.com/FlashpointProject/flashpoint-submission-system/utils"
"github.com/sirupsen/logrus"
)
func (s *SiteService) RunNotificationConsumer(logger *logrus.Entry, ctx context.Context, wg *sync.WaitGroup) {
defer wg.Done()
l := logger.WithField("serviceName", "notificationConsumer")
defer l.Info("notification consumer stopped")
bucket, ticker := utils.NewBucketLimiter(10*time.Millisecond, 1)
defer ticker.Stop()
s.announceNotification()
const errorSleepTime = time.Second * 60
for {
select {
case <-ctx.Done():
l.Info("context cancelled, stopping notification consumer")
return
case <-s.notificationQueueNotEmpty:
select {
case <-ctx.Done():
l.Info("context cancelled, stopping notification consumer")
return
case <-bucket:
}
// TODO yea, like this is fetching notifications one by one, which is lovely and simple,
// but also has some room for optimizing database access
loopWrap := func() {
dbs, err := s.dal.NewSession(ctx)
if err != nil {
if err == context.Canceled {
return
}
l.Error(err)
l.Debugf("sleeping for %f seconds", errorSleepTime.Seconds())
time.Sleep(errorSleepTime)
return
}
defer dbs.Rollback()
notification, err := s.dal.GetOldestUnsentNotification(dbs)
if err != nil {
if err == context.Canceled {
return
}
if err == sql.ErrNoRows {
l.Debug("notification queue is empty, waiting for announcement to resume consumption")
return
}
l.Error(err)
l.Debugf("sleeping for %f seconds", errorSleepTime.Seconds())
time.Sleep(errorSleepTime)
return
}
s.announceNotification()
if err := s.notificationBot.SendNotification(notification.Message, notification.Type); err != nil {
l.Error(err)
l.Debugf("sleeping for %f seconds", errorSleepTime.Seconds())
time.Sleep(errorSleepTime)
return
}
if err := s.dal.MarkNotificationAsSent(dbs, notification.ID); err != nil {
if err == context.Canceled {
return
}
l.Error(err)
l.Debugf("sleeping for %f seconds", errorSleepTime.Seconds())
time.Sleep(errorSleepTime)
return
}
if err := dbs.Commit(); err != nil {
if err == context.Canceled {
return
}
l.Error(err)
l.Debugf("sleeping for %f seconds", errorSleepTime.Seconds())
time.Sleep(errorSleepTime)
return
}
}
loopWrap()
}
}
}
func (s *SiteService) announceNotification() {
select {
// non-blocking announce that something is in the queue
case s.notificationQueueNotEmpty <- true:
default:
}
}