topic.go 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  1. package server
  2. import (
  3. "heckel.io/ntfy/log"
  4. "math/rand"
  5. "sync"
  6. "time"
  7. )
  8. const (
  9. topicExpiryDuration = 6 * time.Hour
  10. )
  11. // topic represents a channel to which subscribers can subscribe, and publishers
  12. // can publish a message
  13. type topic struct {
  14. ID string
  15. subscribers map[int]*topicSubscriber
  16. rateVisitor *visitor
  17. expires time.Time
  18. mu sync.RWMutex
  19. }
  20. type topicSubscriber struct {
  21. subscriber subscriber
  22. visitor *visitor // User ID associated with this subscription, may be empty
  23. cancel func()
  24. }
  25. // subscriber is a function that is called for every new message on a topic
  26. type subscriber func(v *visitor, msg *message) error
  27. // newTopic creates a new topic
  28. func newTopic(id string) *topic {
  29. return &topic{
  30. ID: id,
  31. subscribers: make(map[int]*topicSubscriber),
  32. }
  33. }
  34. // Subscribe subscribes to this topic
  35. func (t *topic) Subscribe(s subscriber, visitor *visitor, cancel func()) int {
  36. t.mu.Lock()
  37. defer t.mu.Unlock()
  38. subscriberID := rand.Int()
  39. t.subscribers[subscriberID] = &topicSubscriber{
  40. visitor: visitor, // May be empty
  41. subscriber: s,
  42. cancel: cancel,
  43. }
  44. return subscriberID
  45. }
  46. func (t *topic) Stale() bool {
  47. t.mu.Lock()
  48. defer t.mu.Unlock()
  49. return len(t.subscribers) == 0 && t.expires.Before(time.Now())
  50. }
  51. func (t *topic) SetRateVisitor(v *visitor) {
  52. t.mu.Lock()
  53. defer t.mu.Unlock()
  54. t.rateVisitor = v
  55. }
  56. func (t *topic) RateVisitor() *visitor {
  57. t.mu.Lock()
  58. defer t.mu.Unlock()
  59. return t.rateVisitor
  60. }
  61. // Unsubscribe removes the subscription from the list of subscribers
  62. func (t *topic) Unsubscribe(id int) {
  63. t.mu.Lock()
  64. defer t.mu.Unlock()
  65. delete(t.subscribers, id)
  66. if len(t.subscribers) == 0 {
  67. t.expires = time.Now().Add(topicExpiryDuration)
  68. }
  69. }
  70. // Publish asynchronously publishes to all subscribers
  71. func (t *topic) Publish(v *visitor, m *message) error {
  72. go func() {
  73. // We want to lock the topic as short as possible, so we make a shallow copy of the
  74. // subscribers map here. Actually sending out the messages then doesn't have to lock.
  75. subscribers := t.subscribersCopy()
  76. if len(subscribers) > 0 {
  77. logvm(v, m).Tag(tagPublish).Debug("Forwarding to %d subscriber(s)", len(subscribers))
  78. for _, s := range subscribers {
  79. // We call the subscriber functions in their own Go routines because they are blocking, and
  80. // we don't want individual slow subscribers to be able to block others.
  81. go func(s subscriber) {
  82. if err := s(v, m); err != nil {
  83. logvm(v, m).Tag(tagPublish).Err(err).Warn("Error forwarding to subscriber")
  84. }
  85. }(s.subscriber)
  86. }
  87. } else {
  88. logvm(v, m).Tag(tagPublish).Trace("No stream or WebSocket subscribers, not forwarding")
  89. }
  90. }()
  91. return nil
  92. }
  93. // SubscribersCount returns the number of subscribers to this topic
  94. func (t *topic) SubscribersCount() int {
  95. t.mu.RLock()
  96. defer t.mu.RUnlock()
  97. return len(t.subscribers)
  98. }
  99. // CancelSubscribers calls the cancel function for all subscribers, forcing
  100. func (t *topic) CancelSubscribers(exceptUserID string) {
  101. t.mu.Lock()
  102. defer t.mu.Unlock()
  103. for _, s := range t.subscribers {
  104. if s.visitor.MaybeUserID() != exceptUserID {
  105. // TODO: Shouldn't this log the IP for anonymous visitors? It was s.userID before my change.
  106. log.Tag(tagSubscribe).Field("topic", t.ID).Debug("Canceling subscriber %s", s.visitor.MaybeUserID())
  107. s.cancel()
  108. }
  109. }
  110. }
  111. // subscribersCopy returns a shallow copy of the subscribers map
  112. func (t *topic) subscribersCopy() map[int]*topicSubscriber {
  113. t.mu.Lock()
  114. defer t.mu.Unlock()
  115. subscribers := make(map[int]*topicSubscriber)
  116. for k, sub := range t.subscribers {
  117. subscribers[k] = &topicSubscriber{
  118. visitor: sub.visitor,
  119. subscriber: sub.subscriber,
  120. cancel: sub.cancel,
  121. }
  122. }
  123. return subscribers
  124. }