bus.go 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  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. }
  32. // New creates a Bus with the given buffer size. Use 0 for DefaultBufferSize.
  33. func New(bufSize int) *Bus {
  34. if bufSize <= 0 {
  35. bufSize = DefaultBufferSize
  36. }
  37. b := &Bus{
  38. ch: make(chan Event, bufSize),
  39. done: make(chan struct{}),
  40. }
  41. b.wg.Add(1)
  42. go b.dispatch()
  43. return b
  44. }
  45. // Subscribe registers a handler that receives every published event on its own
  46. // worker goroutine. The id is used for Unsubscribe; it must be unique across
  47. // active subscribers. Subscribing with an already-registered id replaces the
  48. // previous subscriber, stopping its worker.
  49. func (b *Bus) Subscribe(id string, handler func(Event)) {
  50. b.mu.Lock()
  51. defer b.mu.Unlock()
  52. for i, s := range b.subs {
  53. if s.id == id {
  54. close(s.quit)
  55. b.subs = append(b.subs[:i], b.subs[i+1:]...)
  56. break
  57. }
  58. }
  59. s := &subscriber{
  60. id: id,
  61. handler: handler,
  62. queue: make(chan Event, subscriberQueueSize),
  63. quit: make(chan struct{}),
  64. }
  65. b.subs = append(b.subs, s)
  66. b.wg.Add(1)
  67. go b.runWorker(s)
  68. }
  69. // Unsubscribe removes a subscriber by id and stops its worker. Safe to call with an unknown id.
  70. func (b *Bus) Unsubscribe(id string) {
  71. b.mu.Lock()
  72. defer b.mu.Unlock()
  73. for i, s := range b.subs {
  74. if s.id == id {
  75. close(s.quit)
  76. b.subs = append(b.subs[:i], b.subs[i+1:]...)
  77. return
  78. }
  79. }
  80. }
  81. // Publish sends an event to all subscribers. Non-blocking — if the buffer is
  82. // full the event is dropped and a warning is logged.
  83. func (b *Bus) Publish(e Event) {
  84. if e.Timestamp.IsZero() {
  85. e.Timestamp = time.Now()
  86. }
  87. select {
  88. case b.ch <- e:
  89. default:
  90. logger.Warning("eventbus: buffer full, dropping event ", e.Type)
  91. }
  92. }
  93. // dispatch is the fan-out loop. It reads events from the channel and hands each
  94. // one to every subscriber's queue with a non-blocking send, so a subscriber
  95. // whose handler blocks on network I/O (the email and Telegram notifiers can
  96. // block for tens of seconds) can neither stall delivery of unrelated, higher-
  97. // value events such as xray.crash or node.down, nor force the bus to spawn an
  98. // unbounded number of goroutines under load. A subscriber whose queue is full
  99. // drops the event, keeping the bus non-blocking and its memory bounded.
  100. func (b *Bus) dispatch() {
  101. defer b.wg.Done()
  102. for {
  103. select {
  104. case e, ok := <-b.ch:
  105. if !ok {
  106. return
  107. }
  108. b.mu.RLock()
  109. for _, s := range b.subs {
  110. select {
  111. case s.queue <- e:
  112. default:
  113. logger.Warning("eventbus: subscriber ", s.id, " queue full, dropping ", e.Type)
  114. }
  115. }
  116. b.mu.RUnlock()
  117. case <-b.done:
  118. return
  119. }
  120. }
  121. }
  122. // runWorker delivers queued events to one subscriber serially, so a subscriber
  123. // never runs concurrently with itself and observes events in publication order.
  124. func (b *Bus) runWorker(s *subscriber) {
  125. defer b.wg.Done()
  126. for {
  127. select {
  128. case e := <-s.queue:
  129. safeCall(s.handler, e)
  130. case <-s.quit:
  131. return
  132. case <-b.done:
  133. return
  134. }
  135. }
  136. }
  137. // safeCall invokes handler with panic recovery.
  138. func safeCall(fn func(Event), e Event) {
  139. defer func() {
  140. if r := recover(); r != nil {
  141. logger.Errorf("eventbus: subscriber panicked on %s: %v", e.Type, r)
  142. }
  143. }()
  144. fn(e)
  145. }
  146. // Stop shuts down the bus: the dispatch loop and every subscriber worker exit
  147. // after finishing any handler already in progress, and any events still buffered
  148. // or queued may be dropped. Safe to call once.
  149. func (b *Bus) Stop() {
  150. close(b.done)
  151. b.wg.Wait()
  152. }