Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[alt] using channel for keep block order #93

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 11 additions & 40 deletions pkg/listener/listener.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,39 +70,6 @@ func New(
}
}

func (l *Listener) publishBlock(ch chan<- types.Block, seq uint64, block *types.Block) {
if l.queue == nil {
ch <- *block

return
}

expectedSeq := l.queue.SequenceNumber()
if seq < expectedSeq {
return
}

if int(seq-expectedSeq) >= l.maxQueueLen {
for i := 0; i <= int(seq-expectedSeq)-l.maxQueueLen; i++ {
b, _ := l.queue.Dequeue()
if b != nil {
ch <- *b
}
}
}

l.queue.Insert(seq, block)
for !l.queue.Empty() {
b, _ := l.queue.Peek()
if b == nil {
return
}

ch <- *b
l.queue.Dequeue()
}
}

func (l *Listener) handleNewHeader(ctx context.Context, header *types.Header) (types.Block, error) {
var err error
var logs []types.Log
Expand Down Expand Up @@ -221,7 +188,12 @@ func (l *Listener) subscribeNewBlockHead(ctx context.Context, blockCh chan<- typ
return err
}

seq := uint64(1)
sequenceCh := make(chan chan types.Block, l.maxQueueLen)
go func() {
for orderedBlockCh := range sequenceCh {
blockCh <- (<-orderedBlockCh)
}
}()
for {
select {
case <-ctx.Done():
Expand All @@ -246,16 +218,15 @@ func (l *Listener) subscribeNewBlockHead(ctx context.Context, blockCh chan<- typ
}
l.mu.Unlock()

go func(seq uint64, head *types.Header) {
ch := make(chan types.Block)
sequenceCh <- ch
go func(head *types.Header, ch chan types.Block) {
b, err := l.handleNewHeader(ctx, head)
if err != nil {
l.l.Fatalw("Fail to handle new head", "header", header, "error", err)
}

l.publishBlock(blockCh, seq, &b)
}(seq, header)

seq++
ch <- b
}(header, ch)
}
}
}
Expand Down
Loading