topic.go 4.7 KB

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