Skip to content

Commit

Permalink
fix: make ranges.Add thread-safe
Browse files Browse the repository at this point in the history
  • Loading branch information
tzdybal committed Jan 27, 2023
1 parent a30039c commit cde501d
Showing 1 changed file with 8 additions and 4 deletions.
12 changes: 8 additions & 4 deletions libs/header/sync/ranges.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ func (rs *ranges[H]) Head() H {
rs.lk.RLock()
defer rs.lk.RUnlock()

return rs.head()
}

func (rs *ranges[H]) head() H {
ln := len(rs.ranges)
if ln == 0 {
var zero H
Expand All @@ -32,7 +36,10 @@ func (rs *ranges[H]) Head() H {
// Add appends the new Header to existing range or starts a new one.
// It starts a new one if the new Header is not adjacent to any of existing ranges.
func (rs *ranges[H]) Add(h H) {
head := rs.Head()
rs.lk.Lock()
defer rs.lk.Unlock()

head := rs.head()

// short-circuit if header is from the past
if !head.IsZero() && head.Height() >= h.Height() {
Expand All @@ -47,9 +54,6 @@ func (rs *ranges[H]) Add(h H) {
return
}

rs.lk.Lock()
defer rs.lk.Unlock()

// if the new header is adjacent to head
if !head.IsZero() && h.Height() == head.Height()+1 {
// append it to the last known range
Expand Down

0 comments on commit cde501d

Please sign in to comment.