1
0
Fork 0
mirror of https://github.com/binwiederhier/ntfy.git synced 2025-05-23 07:17:37 +02:00

Fix tests, lock topic as short as possible

This commit is contained in:
Philipp Heckel 2022-06-21 19:45:23 -04:00
parent 85f2252a77
commit c1f7bed8d1
3 changed files with 33 additions and 20 deletions
server

View file

@ -44,11 +44,12 @@ func (t *topic) Unsubscribe(id int) {
// Publish asynchronously publishes to all subscribers
func (t *topic) Publish(v *visitor, m *message) error {
go func() {
t.mu.Lock()
defer t.mu.Unlock()
if len(t.subscribers) > 0 {
log.Debug("%s Forwarding to %d subscriber(s)", logMessagePrefix(v, m), len(t.subscribers))
for _, s := range t.subscribers {
// We want to lock the topic as short as possible, so we make a shallow copy of the
// subscribers map here. Actually sending out the messages then doesn't have to lock.
subscribers := t.subscribersCopy()
if len(subscribers) > 0 {
log.Debug("%s Forwarding to %d subscriber(s)", logMessagePrefix(v, m), len(subscribers))
for _, s := range subscribers {
if err := s(v, m); err != nil {
log.Warn("%s Error forwarding to subscriber", logMessagePrefix(v, m))
}
@ -60,9 +61,20 @@ func (t *topic) Publish(v *visitor, m *message) error {
return nil
}
// Subscribers returns the number of subscribers to this topic
func (t *topic) Subscribers() int {
// SubscribersCount returns the number of subscribers to this topic
func (t *topic) SubscribersCount() int {
t.mu.Lock()
defer t.mu.Unlock()
return len(t.subscribers)
}
// subscribersCopy returns a shallow copy of the subscribers map
func (t *topic) subscribersCopy() map[int]subscriber {
t.mu.Lock()
defer t.mu.Unlock()
subscribers := make(map[int]subscriber)
for k, v := range t.subscribers {
subscribers[k] = v
}
return subscribers
}