feed.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  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. rvalue := reflect.ValueOf(value)
  115. f.once.Do(f.init)
  116. <-f.sendLock
  117. // Add new cases from the inbox after taking the send lock.
  118. f.mu.Lock()
  119. f.sendCases = append(f.sendCases, f.inbox...)
  120. f.inbox = nil
  121. if !f.typecheck(rvalue.Type()) {
  122. f.sendLock <- struct{}{}
  123. panic(feedTypeError{op: "Send", got: rvalue.Type(), want: f.etype})
  124. }
  125. f.mu.Unlock()
  126. // Set the sent value on all channels.
  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. 'cases' tracks a prefix
  131. // of sendCases. When a send succeeds, the corresponding case moves to the end of
  132. // 'cases' and it shrinks by one element.
  133. cases := f.sendCases
  134. for {
  135. // Fast path: try sending without blocking before adding to the select set.
  136. // This should usually succeed if subscribers are fast enough and have free
  137. // buffer space.
  138. for i := firstSubSendCase; i < len(cases); i++ {
  139. if cases[i].Chan.TrySend(rvalue) {
  140. nsent++
  141. cases = cases.deactivate(i)
  142. i--
  143. }
  144. }
  145. if len(cases) == firstSubSendCase {
  146. break
  147. }
  148. // Select on all the receivers, waiting for them to unblock.
  149. chosen, recv, _ := reflect.Select(cases)
  150. if chosen == 0 /* <-f.removeSub */ {
  151. index := f.sendCases.find(recv.Interface())
  152. f.sendCases = f.sendCases.delete(index)
  153. if index >= 0 && index < len(cases) {
  154. // Shrink 'cases' too because the removed case was still active.
  155. cases = f.sendCases[:len(cases)-1]
  156. }
  157. } else {
  158. cases = cases.deactivate(chosen)
  159. nsent++
  160. }
  161. }
  162. // Forget about the sent value and hand off the send lock.
  163. for i := firstSubSendCase; i < len(f.sendCases); i++ {
  164. f.sendCases[i].Send = reflect.Value{}
  165. }
  166. f.sendLock <- struct{}{}
  167. return nsent
  168. }
  169. type feedSub struct {
  170. feed *Feed
  171. channel reflect.Value
  172. errOnce sync.Once
  173. err chan error
  174. }
  175. func (sub *feedSub) Unsubscribe() {
  176. sub.errOnce.Do(func() {
  177. sub.feed.remove(sub)
  178. close(sub.err)
  179. })
  180. }
  181. func (sub *feedSub) Err() <-chan error {
  182. return sub.err
  183. }
  184. type caseList []reflect.SelectCase
  185. // find returns the index of a case containing the given channel.
  186. func (cs caseList) find(channel interface{}) int {
  187. for i, cas := range cs {
  188. if cas.Chan.Interface() == channel {
  189. return i
  190. }
  191. }
  192. return -1
  193. }
  194. // delete removes the given case from cs.
  195. func (cs caseList) delete(index int) caseList {
  196. return append(cs[:index], cs[index+1:]...)
  197. }
  198. // deactivate moves the case at index into the non-accessible portion of the cs slice.
  199. func (cs caseList) deactivate(index int) caseList {
  200. last := len(cs) - 1
  201. cs[index], cs[last] = cs[last], cs[index]
  202. return cs[:last]
  203. }
  204. // func (cs caseList) String() string {
  205. // s := "["
  206. // for i, cas := range cs {
  207. // if i != 0 {
  208. // s += ", "
  209. // }
  210. // switch cas.Dir {
  211. // case reflect.SelectSend:
  212. // s += fmt.Sprintf("%v<-", cas.Chan.Interface())
  213. // case reflect.SelectRecv:
  214. // s += fmt.Sprintf("<-%v", cas.Chan.Interface())
  215. // }
  216. // }
  217. // return s + "]"
  218. // }