topic.go 4.4 KB

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