feed.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. // Copyright 2016 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
  17. import (
  18. "errors"
  19. "reflect"
  20. "sync"
  21. )
  22. var errBadChannel = errors.New("event: Subscribe argument does not have sendable channel type")
  23. // Feed implements one-to-many subscriptions where the carrier of events is a channel.
  24. // Values sent to a Feed are delivered to all subscribed channels simultaneously.
  25. //
  26. // Feeds can only be used with a single type. The type is determined by the first Send or
  27. // Subscribe operation. Subsequent calls to these methods panic if the type does not
  28. // match.
  29. //
  30. // The zero value is ready to use.
  31. type Feed struct {
  32. once sync.Once // ensures that init only runs once
  33. sendLock chan struct{} // sendLock has a one-element buffer and is empty when held.It protects sendCases.
  34. removeSub chan interface{} // interrupts Send
  35. sendCases caseList // the active set of select cases used by Send
  36. // The inbox holds newly subscribed channels until they are added to sendCases.
  37. mu sync.Mutex
  38. inbox caseList
  39. etype reflect.Type
  40. closed bool
  41. }
  42. // This is the index of the first actual subscription channel in sendCases.
  43. // sendCases[0] is a SelectRecv case for the removeSub channel.
  44. const firstSubSendCase = 1
  45. type feedTypeError struct {
  46. got, want reflect.Type
  47. op string
  48. }
  49. func (e feedTypeError) Error() string {
  50. return "event: wrong type in " + e.op + " got " + e.got.String() + ", want " + e.want.String()
  51. }
  52. func (f *Feed) init() {
  53. f.removeSub = make(chan interface{})
  54. f.sendLock = make(chan struct{}, 1)
  55. f.sendLock <- struct{}{}
  56. f.sendCases = caseList{{Chan: reflect.ValueOf(f.removeSub), Dir: reflect.SelectRecv}}
  57. }
  58. // Subscribe adds a channel to the feed. Future sends will be delivered on the channel
  59. // until the subscription is canceled. All channels added must have the same element type.
  60. //
  61. // The channel should have ample buffer space to avoid blocking other subscribers.
  62. // Slow subscribers are not dropped.
  63. func (f *Feed) Subscribe(channel interface{}) Subscription {
  64. f.once.Do(f.init)
  65. chanval := reflect.ValueOf(channel)
  66. chantyp := chanval.Type()
  67. if chantyp.Kind() != reflect.Chan || chantyp.ChanDir()&reflect.SendDir == 0 {
  68. panic(errBadChannel)
  69. }
  70. sub := &feedSub{feed: f, channel: chanval, err: make(chan error, 1)}
  71. f.mu.Lock()
  72. defer f.mu.Unlock()
  73. if !f.typecheck(chantyp.Elem()) {
  74. panic(feedTypeError{op: "Subscribe", got: chantyp, want: reflect.ChanOf(reflect.SendDir, f.etype)})
  75. }
  76. // Add the select case to the inbox.
  77. // The next Send will add it to f.sendCases.
  78. cas := reflect.SelectCase{Dir: reflect.SelectSend, Chan: chanval}
  79. f.inbox = append(f.inbox, cas)
  80. return sub
  81. }
  82. // note: callers must hold f.mu
  83. func (f *Feed) typecheck(typ reflect.Type) bool {
  84. if f.etype == nil {
  85. f.etype = typ
  86. return true
  87. }
  88. return f.etype == typ
  89. }
  90. func (f *Feed) remove(sub *feedSub) {
  91. // Delete from inbox first, which covers channels
  92. // that have not been added to f.sendCases yet.
  93. ch := sub.channel.Interface()
  94. f.mu.Lock()
  95. index := f.inbox.find(ch)
  96. if index != -1 {
  97. f.inbox = f.inbox.delete(index)
  98. f.mu.Unlock()
  99. return
  100. }
  101. f.mu.Unlock()
  102. select {
  103. case f.removeSub <- ch:
  104. // Send will remove the channel from f.sendCases.
  105. case <-f.sendLock:
  106. // No Send is in progress, delete the channel now that we have the send lock.
  107. f.sendCases = f.sendCases.delete(f.sendCases.find(ch))
  108. f.sendLock <- struct{}{}
  109. }
  110. }
  111. // Send delivers to all subscribed channels simultaneously.
  112. // It returns the number of subscribers that the value was sent to.
  113. func (f *Feed) Send(value interface{}) (nsent int) {
  114. f.once.Do(f.init)
  115. <-f.sendLock
  116. // Add new cases from the inbox after taking the send lock.
  117. f.mu.Lock()
  118. f.sendCases = append(f.sendCases, f.inbox...)
  119. f.inbox = nil
  120. f.mu.Unlock()
  121. // Set the sent value on all channels.
  122. rvalue := reflect.ValueOf(value)
  123. if !f.typecheck(rvalue.Type()) {
  124. f.sendLock <- struct{}{}
  125. panic(feedTypeError{op: "Send", got: rvalue.Type(), want: f.etype})
  126. }
  127. for i := firstSubSendCase; i < len(f.sendCases); i++ {
  128. f.sendCases[i].Send = rvalue
  129. }
  130. // Send until all channels except removeSub have been chosen.
  131. cases := f.sendCases
  132. for {
  133. // Fast path: try sending without blocking before adding to the select set.
  134. // This should usually succeed if subscribers are fast enough and have free
  135. // buffer space.
  136. for i := firstSubSendCase; i < len(cases); i++ {
  137. if cases[i].Chan.TrySend(rvalue) {
  138. nsent++
  139. cases = cases.deactivate(i)
  140. i--
  141. }
  142. }
  143. if len(cases) == firstSubSendCase {
  144. break
  145. }
  146. // Select on all the receivers, waiting for them to unblock.
  147. chosen, recv, _ := reflect.Select(cases)
  148. if chosen == 0 /* <-f.removeSub */ {
  149. index := f.sendCases.find(recv.Interface())
  150. f.sendCases = f.sendCases.delete(index)
  151. if index >= 0 && index < len(cases) {
  152. cases = f.sendCases[:len(cases)-1]
  153. }
  154. } else {
  155. cases = cases.deactivate(chosen)
  156. nsent++
  157. }
  158. }
  159. // Forget about the sent value and hand off the send lock.
  160. for i := firstSubSendCase; i < len(f.sendCases); i++ {
  161. f.sendCases[i].Send = reflect.Value{}
  162. }
  163. f.sendLock <- struct{}{}
  164. return nsent
  165. }
  166. type feedSub struct {
  167. feed *Feed
  168. channel reflect.Value
  169. errOnce sync.Once
  170. err chan error
  171. }
  172. func (sub *feedSub) Unsubscribe() {
  173. sub.errOnce.Do(func() {
  174. sub.feed.remove(sub)
  175. close(sub.err)
  176. })
  177. }
  178. func (sub *feedSub) Err() <-chan error {
  179. return sub.err
  180. }
  181. type caseList []reflect.SelectCase
  182. // find returns the index of a case containing the given channel.
  183. func (cs caseList) find(channel interface{}) int {
  184. for i, cas := range cs {
  185. if cas.Chan.Interface() == channel {
  186. return i
  187. }
  188. }
  189. return -1
  190. }
  191. // delete removes the given case from cs.
  192. func (cs caseList) delete(index int) caseList {
  193. return append(cs[:index], cs[index+1:]...)
  194. }
  195. // deactivate moves the case at index into the non-accessible portion of the cs slice.
  196. func (cs caseList) deactivate(index int) caseList {
  197. last := len(cs) - 1
  198. cs[index], cs[last] = cs[last], cs[index]
  199. return cs[:last]
  200. }
  201. // func (cs caseList) String() string {
  202. // s := "["
  203. // for i, cas := range cs {
  204. // if i != 0 {
  205. // s += ", "
  206. // }
  207. // switch cas.Dir {
  208. // case reflect.SelectSend:
  209. // s += fmt.Sprintf("%v<-", cas.Chan.Interface())
  210. // case reflect.SelectRecv:
  211. // s += fmt.Sprintf("<-%v", cas.Chan.Interface())
  212. // }
  213. // }
  214. // return s + "]"
  215. // }