Skip to content

Commit 8e32eeb

Browse files
authored
Hold the event source when there are no listeners (#15725)
* Hold the event source when there are no listeners The event source does not need to run when there are no listeners. Therefore pause it when there are none. * add some more logging Signed-off-by: Andrew Thornton <[email protected]>
1 parent f582ec4 commit 8e32eeb

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

modules/eventsource/manager.go

+6
Original file line numberDiff line numberDiff line change
@@ -13,13 +13,15 @@ type Manager struct {
1313
mutex sync.Mutex
1414

1515
messengers map[int64]*Messenger
16+
connection chan struct{}
1617
}
1718

1819
var manager *Manager
1920

2021
func init() {
2122
manager = &Manager{
2223
messengers: make(map[int64]*Messenger),
24+
connection: make(chan struct{}, 1),
2325
}
2426
}
2527

@@ -36,6 +38,10 @@ func (m *Manager) Register(uid int64) <-chan *Event {
3638
messenger = NewMessenger(uid)
3739
m.messengers[uid] = messenger
3840
}
41+
select {
42+
case m.connection <- struct{}{}:
43+
default:
44+
}
3945
m.mutex.Unlock()
4046
return messenger.Register()
4147
}

modules/eventsource/manager_run.go

+29
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,35 @@ loop:
3434
timer.Stop()
3535
break loop
3636
case <-timer.C:
37+
m.mutex.Lock()
38+
connectionCount := len(m.messengers)
39+
if connectionCount == 0 {
40+
log.Trace("Event source has no listeners")
41+
// empty the connection channel
42+
select {
43+
case <-m.connection:
44+
default:
45+
}
46+
}
47+
m.mutex.Unlock()
48+
if connectionCount == 0 {
49+
// No listeners so the source can be paused
50+
log.Trace("Pausing the eventsource")
51+
select {
52+
case <-ctx.Done():
53+
break loop
54+
case <-m.connection:
55+
log.Trace("Connection detected - restarting the eventsource")
56+
// OK we're back so lets reset the timer and start again
57+
// We won't change the "then" time because there could be concurrency issues
58+
select {
59+
case <-timer.C:
60+
default:
61+
}
62+
continue
63+
}
64+
}
65+
3766
now := timeutil.TimeStampNow().Add(-2)
3867

3968
uidCounts, err := models.GetUIDsAndNotificationCounts(then, now)

0 commit comments

Comments
 (0)