topic.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package server
  2. import (
  3. "heckel.io/ntfy/log"
  4. "math/rand"
  5. "sync"
  6. )
  7. // topic represents a channel to which subscribers can subscribe, and publishers
  8. // can publish a message
  9. type topic struct {
  10. ID string
  11. subscribers map[int]subscriber
  12. mu sync.Mutex
  13. }
  14. // subscriber is a function that is called for every new message on a topic
  15. type subscriber func(v *visitor, msg *message) error
  16. // newTopic creates a new topic
  17. func newTopic(id string) *topic {
  18. return &topic{
  19. ID: id,
  20. subscribers: make(map[int]subscriber),
  21. }
  22. }
  23. // Subscribe subscribes to this topic
  24. func (t *topic) Subscribe(s subscriber) int {
  25. t.mu.Lock()
  26. defer t.mu.Unlock()
  27. subscriberID := rand.Int()
  28. t.subscribers[subscriberID] = s
  29. return subscriberID
  30. }
  31. // Unsubscribe removes the subscription from the list of subscribers
  32. func (t *topic) Unsubscribe(id int) {
  33. t.mu.Lock()
  34. defer t.mu.Unlock()
  35. delete(t.subscribers, id)
  36. }
  37. // Publish asynchronously publishes to all subscribers
  38. func (t *topic) Publish(v *visitor, m *message) error {
  39. go func() {
  40. t.mu.Lock()
  41. defer t.mu.Unlock()
  42. if len(t.subscribers) > 0 {
  43. log.Debug("%s Forwarding to %d subscriber(s)", logMessagePrefix(v, m), len(t.subscribers))
  44. for _, s := range t.subscribers {
  45. if err := s(v, m); err != nil {
  46. log.Warn("%s Error forwarding to subscriber", logMessagePrefix(v, m))
  47. }
  48. }
  49. } else {
  50. log.Trace("%s No stream or WebSocket subscribers, not forwarding", logMessagePrefix(v, m))
  51. }
  52. }()
  53. return nil
  54. }
  55. // Subscribers returns the number of subscribers to this topic
  56. func (t *topic) Subscribers() int {
  57. t.mu.Lock()
  58. defer t.mu.Unlock()
  59. return len(t.subscribers)
  60. }