event.go 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. // Copyright 2014 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. // Package event implements an event multiplexer.
  17. package event
  18. import (
  19. "errors"
  20. "fmt"
  21. "reflect"
  22. "sync"
  23. "time"
  24. )
  25. // Event is a time-tagged notification pushed to subscribers.
  26. type Event struct {
  27. Time time.Time
  28. Data interface{}
  29. }
  30. // Subscription is implemented by event subscriptions.
  31. type Subscription interface {
  32. // Chan returns a channel that carries events.
  33. // Implementations should return the same channel
  34. // for any subsequent calls to Chan.
  35. Chan() <-chan *Event
  36. // Unsubscribe stops delivery of events to a subscription.
  37. // The event channel is closed.
  38. // Unsubscribe can be called more than once.
  39. Unsubscribe()
  40. }
  41. // A TypeMux dispatches events to registered receivers. Receivers can be
  42. // registered to handle events of certain type. Any operation
  43. // called after mux is stopped will return ErrMuxClosed.
  44. //
  45. // The zero value is ready to use.
  46. type TypeMux struct {
  47. mutex sync.RWMutex
  48. subm map[reflect.Type][]*muxsub
  49. stopped bool
  50. }
  51. // ErrMuxClosed is returned when Posting on a closed TypeMux.
  52. var ErrMuxClosed = errors.New("event: mux closed")
  53. // Subscribe creates a subscription for events of the given types. The
  54. // subscription's channel is closed when it is unsubscribed
  55. // or the mux is closed.
  56. func (mux *TypeMux) Subscribe(types ...interface{}) Subscription {
  57. sub := newsub(mux)
  58. mux.mutex.Lock()
  59. defer mux.mutex.Unlock()
  60. if mux.stopped {
  61. close(sub.postC)
  62. } else {
  63. if mux.subm == nil {
  64. mux.subm = make(map[reflect.Type][]*muxsub)
  65. }
  66. for _, t := range types {
  67. rtyp := reflect.TypeOf(t)
  68. oldsubs := mux.subm[rtyp]
  69. if find(oldsubs, sub) != -1 {
  70. panic(fmt.Sprintf("event: duplicate type %s in Subscribe", rtyp))
  71. }
  72. subs := make([]*muxsub, len(oldsubs)+1)
  73. copy(subs, oldsubs)
  74. subs[len(oldsubs)] = sub
  75. mux.subm[rtyp] = subs
  76. }
  77. }
  78. return sub
  79. }
  80. // Post sends an event to all receivers registered for the given type.
  81. // It returns ErrMuxClosed if the mux has been stopped.
  82. func (mux *TypeMux) Post(ev interface{}) error {
  83. event := &Event{
  84. Time: time.Now(),
  85. Data: ev,
  86. }
  87. rtyp := reflect.TypeOf(ev)
  88. mux.mutex.RLock()
  89. if mux.stopped {
  90. mux.mutex.RUnlock()
  91. return ErrMuxClosed
  92. }
  93. subs := mux.subm[rtyp]
  94. mux.mutex.RUnlock()
  95. for _, sub := range subs {
  96. sub.deliver(event)
  97. }
  98. return nil
  99. }
  100. // Stop closes a mux. The mux can no longer be used.
  101. // Future Post calls will fail with ErrMuxClosed.
  102. // Stop blocks until all current deliveries have finished.
  103. func (mux *TypeMux) Stop() {
  104. mux.mutex.Lock()
  105. for _, subs := range mux.subm {
  106. for _, sub := range subs {
  107. sub.closewait()
  108. }
  109. }
  110. mux.subm = nil
  111. mux.stopped = true
  112. mux.mutex.Unlock()
  113. }
  114. func (mux *TypeMux) del(s *muxsub) {
  115. mux.mutex.Lock()
  116. for typ, subs := range mux.subm {
  117. if pos := find(subs, s); pos >= 0 {
  118. if len(subs) == 1 {
  119. delete(mux.subm, typ)
  120. } else {
  121. mux.subm[typ] = posdelete(subs, pos)
  122. }
  123. }
  124. }
  125. s.mux.mutex.Unlock()
  126. }
  127. func find(slice []*muxsub, item *muxsub) int {
  128. for i, v := range slice {
  129. if v == item {
  130. return i
  131. }
  132. }
  133. return -1
  134. }
  135. func posdelete(slice []*muxsub, pos int) []*muxsub {
  136. news := make([]*muxsub, len(slice)-1)
  137. copy(news[:pos], slice[:pos])
  138. copy(news[pos:], slice[pos+1:])
  139. return news
  140. }
  141. type muxsub struct {
  142. mux *TypeMux
  143. created time.Time
  144. closeMu sync.Mutex
  145. closing chan struct{}
  146. closed bool
  147. // these two are the same channel. they are stored separately so
  148. // postC can be set to nil without affecting the return value of
  149. // Chan.
  150. postMu sync.RWMutex
  151. readC <-chan *Event
  152. postC chan<- *Event
  153. }
  154. func newsub(mux *TypeMux) *muxsub {
  155. c := make(chan *Event)
  156. return &muxsub{
  157. mux: mux,
  158. created: time.Now(),
  159. readC: c,
  160. postC: c,
  161. closing: make(chan struct{}),
  162. }
  163. }
  164. func (s *muxsub) Chan() <-chan *Event {
  165. return s.readC
  166. }
  167. func (s *muxsub) Unsubscribe() {
  168. s.mux.del(s)
  169. s.closewait()
  170. }
  171. func (s *muxsub) closewait() {
  172. s.closeMu.Lock()
  173. defer s.closeMu.Unlock()
  174. if s.closed {
  175. return
  176. }
  177. close(s.closing)
  178. s.closed = true
  179. s.postMu.Lock()
  180. close(s.postC)
  181. s.postC = nil
  182. s.postMu.Unlock()
  183. }
  184. func (s *muxsub) deliver(event *Event) {
  185. // Short circuit delivery if stale event
  186. if s.created.After(event.Time) {
  187. return
  188. }
  189. // Otherwise deliver the event
  190. s.postMu.RLock()
  191. defer s.postMu.RUnlock()
  192. select {
  193. case s.postC <- event:
  194. case <-s.closing:
  195. }
  196. }