github.com/amazechain/amc@v0.1.3/modules/event/v2/feed.go (about) 1 // Copyright 2023 The AmazeChain Authors 2 // This file is part of the AmazeChain library. 3 // 4 // The AmazeChain 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 AmazeChain 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 AmazeChain library. If not, see <http://www.gnu.org/licenses/>. 16 17 package v2 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(etype reflect.Type) { 61 f.etype = etype 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 chanval := reflect.ValueOf(channel) 75 chantyp := chanval.Type() 76 if chantyp.Kind() != reflect.Chan || chantyp.ChanDir()&reflect.SendDir == 0 { 77 panic(errBadChannel) 78 } 79 sub := &feedSub{feed: f, channel: chanval, err: make(chan error, 1)} 80 81 f.once.Do(func() { f.init(chantyp.Elem()) }) 82 if f.etype != chantyp.Elem() { 83 panic(feedTypeError{op: "Subscribe", got: chantyp, want: reflect.ChanOf(reflect.SendDir, f.etype)}) 84 } 85 86 f.mu.Lock() 87 defer f.mu.Unlock() 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 func (f *Feed) remove(sub *feedSub) { 96 // Delete from inbox first, which covers channels 97 // that have not been added to f.sendCases yet. 98 ch := sub.channel.Interface() 99 f.mu.Lock() 100 index := f.inbox.find(ch) 101 if index != -1 { 102 f.inbox = f.inbox.delete(index) 103 f.mu.Unlock() 104 return 105 } 106 f.mu.Unlock() 107 108 select { 109 case f.removeSub <- ch: 110 // Send will remove the channel from f.sendCases. 111 case <-f.sendLock: 112 // No Send is in progress, delete the channel now that we have the send lock. 113 f.sendCases = f.sendCases.delete(f.sendCases.find(ch)) 114 f.sendLock <- struct{}{} 115 } 116 } 117 118 // Send delivers to all subscribed channels simultaneously. 119 // It returns the number of subscribers that the value was sent to. 120 func (f *Feed) Send(value interface{}) (nsent int) { 121 rvalue := reflect.ValueOf(value) 122 123 f.once.Do(func() { f.init(rvalue.Type()) }) 124 if f.etype != rvalue.Type() { 125 panic(feedTypeError{op: "Send", got: rvalue.Type(), want: f.etype}) 126 } 127 128 <-f.sendLock 129 130 // Add new cases from the inbox after taking the send lock. 131 f.mu.Lock() 132 f.sendCases = append(f.sendCases, f.inbox...) 133 f.inbox = nil 134 f.mu.Unlock() 135 136 // Set the sent value on all channels. 137 for i := firstSubSendCase; i < len(f.sendCases); i++ { 138 f.sendCases[i].Send = rvalue 139 } 140 141 // Send until all channels except removeSub have been chosen. 'cases' tracks a prefix 142 // of sendCases. When a send succeeds, the corresponding case moves to the end of 143 // 'cases' and it shrinks by one element. 144 cases := f.sendCases 145 for { 146 // Fast path: try sending without blocking before adding to the select set. 147 // This should usually succeed if subscribers are fast enough and have free 148 // buffer space. 149 for i := firstSubSendCase; i < len(cases); i++ { 150 if cases[i].Chan.TrySend(rvalue) { 151 nsent++ 152 cases = cases.deactivate(i) 153 i-- 154 } 155 } 156 if len(cases) == firstSubSendCase { 157 break 158 } 159 // Select on all the receivers, waiting for them to unblock. 160 chosen, recv, _ := reflect.Select(cases) 161 if chosen == 0 /* <-f.removeSub */ { 162 index := f.sendCases.find(recv.Interface()) 163 f.sendCases = f.sendCases.delete(index) 164 if index >= 0 && index < len(cases) { 165 // Shrink 'cases' too because the removed case was still active. 166 cases = f.sendCases[:len(cases)-1] 167 } 168 } else { 169 cases = cases.deactivate(chosen) 170 nsent++ 171 } 172 } 173 174 // Forget about the sent value and hand off the send lock. 175 for i := firstSubSendCase; i < len(f.sendCases); i++ { 176 f.sendCases[i].Send = reflect.Value{} 177 } 178 f.sendLock <- struct{}{} 179 return nsent 180 } 181 182 type feedSub struct { 183 feed *Feed 184 channel reflect.Value 185 errOnce sync.Once 186 err chan error 187 } 188 189 func (sub *feedSub) Unsubscribe() { 190 sub.errOnce.Do(func() { 191 sub.feed.remove(sub) 192 close(sub.err) 193 }) 194 } 195 196 func (sub *feedSub) Err() <-chan error { 197 return sub.err 198 } 199 200 type caseList []reflect.SelectCase 201 202 // find returns the index of a case containing the given channel. 203 func (cs caseList) find(channel interface{}) int { 204 for i, cas := range cs { 205 if cas.Chan.Interface() == channel { 206 return i 207 } 208 } 209 return -1 210 } 211 212 // delete removes the given case from cs. 213 func (cs caseList) delete(index int) caseList { 214 return append(cs[:index], cs[index+1:]...) 215 } 216 217 // deactivate moves the case at index into the non-accessible portion of the cs slice. 218 func (cs caseList) deactivate(index int) caseList { 219 last := len(cs) - 1 220 cs[index], cs[last] = cs[last], cs[index] 221 return cs[:last] 222 } 223 224 // func (cs caseList) String() string { 225 // s := "[" 226 // for i, cas := range cs { 227 // if i != 0 { 228 // s += ", " 229 // } 230 // switch cas.Dir { 231 // case reflect.SelectSend: 232 // s += fmt.Sprintf("%v<-", cas.Chan.Interface()) 233 // case reflect.SelectRecv: 234 // s += fmt.Sprintf("<-%v", cas.Chan.Interface()) 235 // } 236 // } 237 // return s + "]" 238 // }