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