Skip to content

Commit

Permalink
Use buffered channel (#1361)
Browse files Browse the repository at this point in the history
  • Loading branch information
goran-ethernal authored Apr 7, 2023
1 parent 0592e11 commit eb45dba
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 22 deletions.
25 changes: 3 additions & 22 deletions blockchain/subscription.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,19 +42,7 @@ type subscription struct {

// GetEventCh creates a new event channel, and returns it
func (s *subscription) GetEventCh() chan *Event {
eventCh := make(chan *Event)

go func() {
for {
evnt := s.GetEvent()
if evnt == nil {
return
}
eventCh <- evnt
}
}()

return eventCh
return s.updateCh
}

// GetEvent returns the event from the subscription (BLOCKING)
Expand Down Expand Up @@ -161,11 +149,7 @@ func (e *eventStream) newUpdateCh() chan *Event {
e.Lock()
defer e.Unlock()

ch := make(chan *Event, 1)

if e.updateCh == nil {
e.updateCh = make([]chan *Event, 0)
}
ch := make(chan *Event, 5)

e.updateCh = append(e.updateCh, ch)

Expand All @@ -179,9 +163,6 @@ func (e *eventStream) push(event *Event) {

// Notify the listeners
for _, update := range e.updateCh {
select {
case update <- event:
default:
}
update <- event
}
}
58 changes: 58 additions & 0 deletions blockchain/subscription_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,3 +51,61 @@ func TestSubscription(t *testing.T) {

assert.Equal(t, event.NewChain[0].Number, caughtEventNum)
}

func TestSubscription_BufferedChannel_MultipleSubscriptions(t *testing.T) {
t.Parallel()

var (
e = &eventStream{}
wg sync.WaitGroup
numOfEvents = 100000
numOfSubscriptions = 10
)

subscriptions := make([]*subscription, numOfSubscriptions)
wg.Add(numOfSubscriptions)

worker := func(id int, sub *subscription) {
updateCh := sub.GetEventCh()
caughtEvents := 0

defer wg.Done()

for {
select {
case <-updateCh:
caughtEvents++
if caughtEvents == numOfEvents {
return
}
case <-time.After(10 * time.Second):
t.Errorf("subscription %d did not caught all events", id)
}
}
}

for i := 0; i < numOfSubscriptions; i++ {
sub := e.subscribe()
subscriptions[i] = sub

go worker(i, sub)
}

// Send the events to the channels
for i := 0; i < numOfEvents; i++ {
e.push(&Event{
NewChain: []*types.Header{
{
Number: uint64(i),
},
},
})
}

// Wait for the events to be processed
wg.Wait()

for _, s := range subscriptions {
s.Close()
}
}

0 comments on commit eb45dba

Please sign in to comment.