github.com/zignig/go-ipfs@v0.0.0-20141111235910-c9e5fdf55a52/exchange/bitswap/strategy/ledger.go (about) 1 package strategy 2 3 import ( 4 "time" 5 6 peer "github.com/jbenet/go-ipfs/peer" 7 u "github.com/jbenet/go-ipfs/util" 8 ) 9 10 // keySet is just a convenient alias for maps of keys, where we only care 11 // access/lookups. 12 type keySet map[u.Key]struct{} 13 14 func newLedger(p peer.Peer, strategy strategyFunc) *ledger { 15 return &ledger{ 16 wantList: keySet{}, 17 Strategy: strategy, 18 Partner: p, 19 } 20 } 21 22 // ledger stores the data exchange relationship between two peers. 23 // NOT threadsafe 24 type ledger struct { 25 // Partner is the remote Peer. 26 Partner peer.Peer 27 28 // Accounting tracks bytes sent and recieved. 29 Accounting debtRatio 30 31 // firstExchnage is the time of the first data exchange. 32 firstExchange time.Time 33 34 // lastExchange is the time of the last data exchange. 35 lastExchange time.Time 36 37 // exchangeCount is the number of exchanges with this peer 38 exchangeCount uint64 39 40 // wantList is a (bounded, small) set of keys that Partner desires. 41 wantList keySet 42 43 Strategy strategyFunc 44 } 45 46 func (l *ledger) ShouldSend() bool { 47 return l.Strategy(l) 48 } 49 50 func (l *ledger) SentBytes(n int) { 51 l.exchangeCount++ 52 l.lastExchange = time.Now() 53 l.Accounting.BytesSent += uint64(n) 54 } 55 56 func (l *ledger) ReceivedBytes(n int) { 57 l.exchangeCount++ 58 l.lastExchange = time.Now() 59 l.Accounting.BytesRecv += uint64(n) 60 } 61 62 // TODO: this needs to be different. We need timeouts. 63 func (l *ledger) Wants(k u.Key) { 64 l.wantList[k] = struct{}{} 65 } 66 67 func (l *ledger) WantListContains(k u.Key) bool { 68 _, ok := l.wantList[k] 69 return ok 70 } 71 72 func (l *ledger) ExchangeCount() uint64 { 73 return l.exchangeCount 74 }