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