bus.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. package eventbus
  2. import (
  3. "sync"
  4. "time"
  5. "github.com/mhsanaei/3x-ui/v3/internal/logger"
  6. )
  7. // DefaultBufferSize is the number of events the bus can hold before Publish starts dropping.
  8. const DefaultBufferSize = 256
  9. // subscriberQueueSize bounds how many undelivered events a single subscriber may
  10. // hold before the newest are dropped. Each subscriber drains its own queue on a
  11. // dedicated worker goroutine, so a slow subscriber can neither stall delivery to
  12. // the others nor make the bus spawn an unbounded number of goroutines.
  13. const subscriberQueueSize = 64
  14. // subscriber pairs an ID with its event handler and the per-subscriber worker
  15. // state used to deliver events to it serially, without blocking the dispatch loop.
  16. type subscriber struct {
  17. id string
  18. handler func(Event)
  19. queue chan Event
  20. quit chan struct{}
  21. }
  22. // Bus is a minimal in-process pub/sub event bus backed by a buffered channel.
  23. // Producers call Publish (non-blocking) and every event is fanned out to all
  24. // subscribers; per-event filtering is the subscriber's responsibility.
  25. type Bus struct {
  26. ch chan Event
  27. subs []*subscriber
  28. mu sync.RWMutex
  29. done chan struct{}
  30. wg sync.WaitGroup
  31. stopped bool
  32. }
  33. // New creates a Bus with the given buffer size. Use 0 for DefaultBufferSize.
  34. func New(bufSize int) *Bus {
  35. if bufSize <= 0 {
  36. bufSize = DefaultBufferSize
  37. }
  38. b := &Bus{
  39. ch: make(chan Event, bufSize),
  40. done: make(chan struct{}),
  41. }
  42. b.wg.Add(1)
  43. go b.dispatch()
  44. return b
  45. }
  46. // Subscribe registers a handler that receives every published event on its own
  47. // worker goroutine. The id is used for Unsubscribe; it must be unique across
  48. // active subscribers. Subscribing with an already-registered id replaces the
  49. // previous subscriber, stopping its worker.
  50. func (b *Bus) Subscribe(id string, handler func(Event)) {
  51. b.mu.Lock()
  52. defer b.mu.Unlock()
  53. if b.stopped {
  54. return
  55. }
  56. for i, s := range b.subs {
  57. if s.id == id {
  58. close(s.quit)
  59. b.subs = append(b.subs[:i], b.subs[i+1:]...)
  60. break
  61. }
  62. }
  63. s := &subscriber{
  64. id: id,
  65. handler: handler,
  66. queue: make(chan Event, subscriberQueueSize),
  67. quit: make(chan struct{}),
  68. }
  69. b.subs = append(b.subs, s)
  70. b.wg.Add(1)
  71. go b.runWorker(s)
  72. }
  73. // Unsubscribe removes a subscriber by id and stops its worker. Safe to call with an unknown id.
  74. func (b *Bus) Unsubscribe(id string) {
  75. b.mu.Lock()
  76. defer b.mu.Unlock()
  77. for i, s := range b.subs {
  78. if s.id == id {
  79. close(s.quit)
  80. b.subs = append(b.subs[:i], b.subs[i+1:]...)
  81. return
  82. }
  83. }
  84. }
  85. // Publish sends an event to all subscribers. Non-blocking — if the buffer is
  86. // full the event is dropped and a warning is logged.
  87. func (b *Bus) Publish(e Event) {
  88. if e.Timestamp.IsZero() {
  89. e.Timestamp = time.Now()
  90. }
  91. select {
  92. case b.ch <- e:
  93. default:
  94. logger.Warning("eventbus: buffer full, dropping event ", e.Type)
  95. }
  96. }
  97. // dispatch is the fan-out loop. It reads events from the channel and hands each
  98. // one to every subscriber's queue with a non-blocking send, so a subscriber
  99. // whose handler blocks on network I/O (the email and Telegram notifiers can
  100. // block for tens of seconds) can neither stall delivery of unrelated, higher-
  101. // value events such as xray.crash or node.down, nor force the bus to spawn an
  102. // unbounded number of goroutines under load. A subscriber whose queue is full
  103. // drops the event, keeping the bus non-blocking and its memory bounded.
  104. func (b *Bus) dispatch() {
  105. defer b.wg.Done()
  106. for {
  107. select {
  108. case e, ok := <-b.ch:
  109. if !ok {
  110. return
  111. }
  112. b.mu.RLock()
  113. for _, s := range b.subs {
  114. select {
  115. case s.queue <- e:
  116. default:
  117. logger.Warning("eventbus: subscriber ", s.id, " queue full, dropping ", e.Type)
  118. }
  119. }
  120. b.mu.RUnlock()
  121. case <-b.done:
  122. return
  123. }
  124. }
  125. }
  126. // runWorker delivers queued events to one subscriber serially, so a subscriber
  127. // never runs concurrently with itself and observes events in publication order.
  128. func (b *Bus) runWorker(s *subscriber) {
  129. defer b.wg.Done()
  130. for {
  131. select {
  132. case e := <-s.queue:
  133. safeCall(s.handler, e)
  134. case <-s.quit:
  135. return
  136. case <-b.done:
  137. return
  138. }
  139. }
  140. }
  141. // safeCall invokes handler with panic recovery.
  142. func safeCall(fn func(Event), e Event) {
  143. defer func() {
  144. if r := recover(); r != nil {
  145. logger.Errorf("eventbus: subscriber panicked on %s: %v", e.Type, r)
  146. }
  147. }()
  148. fn(e)
  149. }
  150. // Stop shuts down the bus: the dispatch loop and every subscriber worker exit
  151. // after finishing any handler already in progress, and any events still buffered
  152. // or queued may be dropped. Safe to call once. After Stop returns, Subscribe is
  153. // a no-op — this also keeps Subscribe's wg.Add from ever racing with Wait below,
  154. // since both are serialized through mu.
  155. func (b *Bus) Stop() {
  156. b.mu.Lock()
  157. b.stopped = true
  158. b.mu.Unlock()
  159. close(b.done)
  160. b.wg.Wait()
  161. }