topic.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. package server
  2. import (
  3. "heckel.io/ntfy/log"
  4. "heckel.io/ntfy/util"
  5. "math/rand"
  6. "sync"
  7. "time"
  8. )
  9. const (
  10. // topicExpungeAfter defines how long a topic is active before it is removed from memory.
  11. // This must be larger than matrixRejectPushKeyForUnifiedPushTopicWithoutRateVisitorAfter to give
  12. // time for more requests to come in, so that we can send a {"rejected":["<pushkey>"]} response back.
  13. topicExpungeAfter = 16 * time.Hour
  14. )
  15. // topic represents a channel to which subscribers can subscribe, and publishers
  16. // can publish a message
  17. type topic struct {
  18. ID string
  19. subscribers map[int]*topicSubscriber
  20. rateVisitor *visitor
  21. lastAccess time.Time
  22. mu sync.RWMutex
  23. }
  24. type topicSubscriber struct {
  25. userID string // User ID associated with this subscription, may be empty
  26. subscriber subscriber
  27. cancel func()
  28. }
  29. // subscriber is a function that is called for every new message on a topic
  30. type subscriber func(v *visitor, msg *message) error
  31. // newTopic creates a new topic
  32. func newTopic(id string) *topic {
  33. return &topic{
  34. ID: id,
  35. subscribers: make(map[int]*topicSubscriber),
  36. lastAccess: time.Now(),
  37. }
  38. }
  39. // Subscribe subscribes to this topic
  40. func (t *topic) Subscribe(s subscriber, userID string, cancel func()) int {
  41. t.mu.Lock()
  42. defer t.mu.Unlock()
  43. subscriberID := rand.Int()
  44. t.subscribers[subscriberID] = &topicSubscriber{
  45. userID: userID, // May be empty
  46. subscriber: s,
  47. cancel: cancel,
  48. }
  49. t.lastAccess = time.Now()
  50. return subscriberID
  51. }
  52. func (t *topic) Stale() bool {
  53. t.mu.Lock()
  54. defer t.mu.Unlock()
  55. if t.rateVisitor != nil && !t.rateVisitor.Stale() {
  56. return false
  57. }
  58. return len(t.subscribers) == 0 && time.Since(t.lastAccess) > topicExpungeAfter
  59. }
  60. func (t *topic) LastAccess() time.Time {
  61. t.mu.RLock()
  62. defer t.mu.RUnlock()
  63. return t.lastAccess
  64. }
  65. func (t *topic) SetRateVisitor(v *visitor) {
  66. t.mu.Lock()
  67. defer t.mu.Unlock()
  68. t.rateVisitor = v
  69. t.lastAccess = time.Now()
  70. }
  71. func (t *topic) RateVisitor() *visitor {
  72. t.mu.Lock()
  73. defer t.mu.Unlock()
  74. if t.rateVisitor != nil && t.rateVisitor.Stale() {
  75. t.rateVisitor = nil
  76. }
  77. return t.rateVisitor
  78. }
  79. // Unsubscribe removes the subscription from the list of subscribers
  80. func (t *topic) Unsubscribe(id int) {
  81. t.mu.Lock()
  82. defer t.mu.Unlock()
  83. delete(t.subscribers, id)
  84. }
  85. // Publish asynchronously publishes to all subscribers
  86. func (t *topic) Publish(v *visitor, m *message) error {
  87. go func() {
  88. // We want to lock the topic as short as possible, so we make a shallow copy of the
  89. // subscribers map here. Actually sending out the messages then doesn't have to lock.
  90. subscribers := t.subscribersCopy()
  91. if len(subscribers) > 0 {
  92. logvm(v, m).Tag(tagPublish).Debug("Forwarding to %d subscriber(s)", len(subscribers))
  93. for _, s := range subscribers {
  94. // We call the subscriber functions in their own Go routines because they are blocking, and
  95. // we don't want individual slow subscribers to be able to block others.
  96. go func(s subscriber) {
  97. if err := s(v, m); err != nil {
  98. logvm(v, m).Tag(tagPublish).Err(err).Warn("Error forwarding to subscriber")
  99. }
  100. }(s.subscriber)
  101. }
  102. } else {
  103. logvm(v, m).Tag(tagPublish).Trace("No stream or WebSocket subscribers, not forwarding")
  104. }
  105. t.Keepalive()
  106. }()
  107. return nil
  108. }
  109. // Stats returns the number of subscribers and last access to this topic
  110. func (t *topic) Stats() (int, time.Time) {
  111. t.mu.RLock()
  112. defer t.mu.RUnlock()
  113. return len(t.subscribers), t.lastAccess
  114. }
  115. // Keepalive sets the last access time and ensures that Stale does not return true
  116. func (t *topic) Keepalive() {
  117. t.mu.Lock()
  118. defer t.mu.Unlock()
  119. t.lastAccess = time.Now()
  120. }
  121. // CancelSubscribers calls the cancel function for all subscribers, forcing
  122. func (t *topic) CancelSubscribers(exceptUserID string) {
  123. t.mu.Lock()
  124. defer t.mu.Unlock()
  125. for _, s := range t.subscribers {
  126. if s.userID != exceptUserID {
  127. log.
  128. Tag(tagSubscribe).
  129. With(t).
  130. Fields(log.Context{
  131. "user_id": s.userID,
  132. }).
  133. Debug("Canceling subscriber %s", s.userID)
  134. s.cancel()
  135. }
  136. }
  137. }
  138. func (t *topic) Context() log.Context {
  139. t.mu.RLock()
  140. defer t.mu.RUnlock()
  141. fields := map[string]any{
  142. "topic": t.ID,
  143. "topic_subscribers": len(t.subscribers),
  144. "topic_last_access": util.FormatTime(t.lastAccess),
  145. }
  146. if t.rateVisitor != nil {
  147. for k, v := range t.rateVisitor.Context() {
  148. fields["topic_rate_"+k] = v
  149. }
  150. }
  151. return fields
  152. }
  153. // subscribersCopy returns a shallow copy of the subscribers map
  154. func (t *topic) subscribersCopy() map[int]*topicSubscriber {
  155. t.mu.Lock()
  156. defer t.mu.Unlock()
  157. subscribers := make(map[int]*topicSubscriber)
  158. for k, sub := range t.subscribers {
  159. subscribers[k] = &topicSubscriber{
  160. userID: sub.userID,
  161. subscriber: sub.subscriber,
  162. cancel: sub.cancel,
  163. }
  164. }
  165. return subscribers
  166. }