Skip to content

Commit

Permalink
fix(bitswap:ledger) race conditions
Browse files Browse the repository at this point in the history
  • Loading branch information
Brian Tiger Chow committed Sep 11, 2014
1 parent 7bae742 commit ad30333
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
23 changes: 23 additions & 0 deletions bitswap/ledger.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package bitswap

import (
"sync"
"time"

peer "github.com/jbenet/go-ipfs/peer"
Expand All @@ -9,6 +10,7 @@ import (

// Ledger stores the data exchange relationship between two peers.
type Ledger struct {
lock sync.RWMutex

// Partner is the remote Peer.
Partner *peer.Peer
Expand All @@ -35,27 +37,48 @@ type Ledger struct {
type LedgerMap map[u.Key]*Ledger

func (l *Ledger) ShouldSend() bool {
l.lock.Lock()
defer l.lock.Unlock()

return l.Strategy(l)
}

func (l *Ledger) SentBytes(n int) {
l.lock.Lock()
defer l.lock.Unlock()

l.exchangeCount++
l.lastExchange = time.Now()
l.Accounting.BytesSent += uint64(n)
}

func (l *Ledger) ReceivedBytes(n int) {
l.lock.Lock()
defer l.lock.Unlock()

l.exchangeCount++
l.lastExchange = time.Now()
l.Accounting.BytesRecv += uint64(n)
}

// TODO: this needs to be different. We need timeouts.
func (l *Ledger) Wants(k u.Key) {
l.lock.Lock()
defer l.lock.Unlock()

l.wantList[k] = struct{}{}
}

func (l *Ledger) WantListContains(k u.Key) bool {
l.lock.RLock()
defer l.lock.RUnlock()

_, ok := l.wantList[k]
return ok
}

func (l *Ledger) ExchangeCount() uint64 {
l.lock.RLock()
defer l.lock.RUnlock()
return l.exchangeCount
}
23 changes: 23 additions & 0 deletions bitswap/ledger_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package bitswap

import (
"sync"
"testing"
)

func TestRaceConditions(t *testing.T) {
const numberOfExpectedExchanges = 10000
l := new(Ledger)
var wg sync.WaitGroup
for i := 0; i < numberOfExpectedExchanges; i++ {
wg.Add(1)
go func() {
defer wg.Done()
l.ReceivedBytes(1)
}()
}
wg.Wait()
if l.ExchangeCount() != numberOfExpectedExchanges {
t.Fail()
}
}

0 comments on commit ad30333

Please sign in to comment.