topic.go 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  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. vRate *visitor
  14. vRateExpires 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.vRate == nil && subscriberRateLimit {
  45. t.vRate = visitor
  46. t.vRateExpires = time.Time{}
  47. }
  48. return subscriberID
  49. }
  50. func (t *topic) Stale() bool {
  51. t.mu.Lock()
  52. defer t.mu.Unlock()
  53. // if Time is initialized (not the zero value) and the expiry time has passed
  54. if !t.vRateExpires.IsZero() && t.vRateExpires.Before(time.Now()) {
  55. t.vRate = nil
  56. }
  57. return len(t.subscribers) == 0 && t.vRate == nil
  58. }
  59. func (t *topic) Billee() *visitor {
  60. t.mu.Lock()
  61. defer t.mu.Unlock()
  62. return t.vRate
  63. }
  64. // Unsubscribe removes the subscription from the list of subscribers
  65. func (t *topic) Unsubscribe(id int) {
  66. t.mu.Lock()
  67. defer t.mu.Unlock()
  68. deletingSub := t.subscribers[id]
  69. delete(t.subscribers, id)
  70. // look for an active subscriber (in random order) that wants to handle the rate limit
  71. for _, v := range t.subscribers {
  72. if v.subscriberRateLimit {
  73. t.vRate = v.visitor
  74. t.vRateExpires = time.Time{}
  75. return
  76. }
  77. }
  78. // if no active subscriber is found, count it towards the leaving subscriber
  79. if deletingSub.subscriberRateLimit {
  80. t.vRate = deletingSub.visitor
  81. t.vRateExpires = time.Now().Add(subscriberBilledValidity)
  82. }
  83. }
  84. // Publish asynchronously publishes to all subscribers
  85. func (t *topic) Publish(v *visitor, m *message) error {
  86. go func() {
  87. // We want to lock the topic as short as possible, so we make a shallow copy of the
  88. // subscribers map here. Actually sending out the messages then doesn't have to lock.
  89. subscribers := t.subscribersCopy()
  90. if len(subscribers) > 0 {
  91. logvm(v, m).Tag(tagPublish).Debug("Forwarding to %d subscriber(s)", len(subscribers))
  92. for _, s := range subscribers {
  93. // We call the subscriber functions in their own Go routines because they are blocking, and
  94. // we don't want individual slow subscribers to be able to block others.
  95. go func(s subscriber) {
  96. if err := s(v, m); err != nil {
  97. logvm(v, m).Tag(tagPublish).Err(err).Warn("Error forwarding to subscriber")
  98. }
  99. }(s.subscriber)
  100. }
  101. } else {
  102. logvm(v, m).Tag(tagPublish).Trace("No stream or WebSocket subscribers, not forwarding")
  103. }
  104. }()
  105. return nil
  106. }
  107. // SubscribersCount returns the number of subscribers to this topic
  108. func (t *topic) SubscribersCount() int {
  109. t.mu.Lock()
  110. defer t.mu.Unlock()
  111. return len(t.subscribers)
  112. }
  113. // CancelSubscribers calls the cancel function for all subscribers, forcing
  114. func (t *topic) CancelSubscribers(exceptUserID string) {
  115. t.mu.Lock()
  116. defer t.mu.Unlock()
  117. for _, s := range t.subscribers {
  118. if s.visitor.MaybeUserID() != exceptUserID {
  119. // TODO: Shouldn't this log the IP for anonymous visitors? It was s.userID before my change.
  120. log.Tag(tagSubscribe).Field("topic", t.ID).Debug("Canceling subscriber %s", s.visitor.MaybeUserID())
  121. s.cancel()
  122. }
  123. }
  124. }
  125. // subscribersCopy returns a shallow copy of the subscribers map
  126. func (t *topic) subscribersCopy() map[int]*topicSubscriber {
  127. t.mu.Lock()
  128. defer t.mu.Unlock()
  129. subscribers := make(map[int]*topicSubscriber)
  130. for k, sub := range t.subscribers {
  131. subscribers[k] = &topicSubscriber{
  132. visitor: sub.visitor,
  133. subscriber: sub.subscriber,
  134. cancel: sub.cancel,
  135. }
  136. }
  137. return subscribers
  138. }