session.go 5.39 KB
Newer Older
Jeromy's avatar
Jeromy committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
package bitswap

import (
	"context"
	"time"

	blocks "github.com/ipfs/go-ipfs/blocks"
	notifications "github.com/ipfs/go-ipfs/exchange/bitswap/notifications"

	logging "gx/ipfs/QmSpJByNKFX1sCsHBEp3R73FL4NF6FnQTEGyNAXHm2GS52/go-log"
	lru "gx/ipfs/QmVYxfoJQiZijTgPNHCHgHELvQpbsJNTg6Crmc3dQkj3yy/golang-lru"
	loggables "gx/ipfs/QmVesPmqbPp7xRGyY96tnBwzDtVV1nqv4SCVxo5zCqKyH8/go-libp2p-loggables"
	cid "gx/ipfs/Qma4RJSuh7mMeJQYCqMbKzekn6EwBo7HEs5AQYjVRMQATB/go-cid"
	peer "gx/ipfs/QmdS9KpbDyPrieswibZhkod1oXqRwZJrUPzxCofAMWpFGq/go-libp2p-peer"
)

const activeWantsLimit = 16

Jeromy's avatar
Jeromy committed
19 20 21
// Session holds state for an individual bitswap transfer operation.
// This allows bitswap to make smarter decisions about who to send wantlist
// info to, and who to request blocks from
Jeromy's avatar
Jeromy committed
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
type Session struct {
	ctx            context.Context
	tofetch        []*cid.Cid
	activePeers    map[peer.ID]struct{}
	activePeersArr []peer.ID

	bs         *Bitswap
	incoming   chan blkRecv
	newReqs    chan []*cid.Cid
	cancelKeys chan []*cid.Cid

	interest  *lru.Cache
	liveWants map[string]time.Time
	liveCnt   int

	tick          *time.Timer
	baseTickDelay time.Duration

	latTotal time.Duration
	fetchcnt int

	notif notifications.PubSub

	uuid logging.Loggable
Jeromy's avatar
Jeromy committed
46 47

	id uint64
Jeromy's avatar
Jeromy committed
48 49
}

Jeromy's avatar
Jeromy committed
50 51
// NewSession creates a new bitswap session whose lifetime is bounded by the
// given context
Jeromy's avatar
Jeromy committed
52 53 54 55 56 57 58 59 60 61 62 63
func (bs *Bitswap) NewSession(ctx context.Context) *Session {
	s := &Session{
		activePeers:   make(map[peer.ID]struct{}),
		liveWants:     make(map[string]time.Time),
		newReqs:       make(chan []*cid.Cid),
		cancelKeys:    make(chan []*cid.Cid),
		ctx:           ctx,
		bs:            bs,
		incoming:      make(chan blkRecv),
		notif:         notifications.New(),
		uuid:          loggables.Uuid("GetBlockRequest"),
		baseTickDelay: time.Millisecond * 500,
Jeromy's avatar
Jeromy committed
64
		id:            bs.getNextSessionID(),
Jeromy's avatar
Jeromy committed
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
	}

	cache, _ := lru.New(2048)
	s.interest = cache

	bs.sessLk.Lock()
	bs.sessions = append(bs.sessions, s)
	bs.sessLk.Unlock()

	go s.run(ctx)

	return s
}

type blkRecv struct {
	from peer.ID
	blk  blocks.Block
}

Jeromy's avatar
Jeromy committed
84
func (s *Session) receiveBlockFrom(from peer.ID, blk blocks.Block) {
Jeromy's avatar
Jeromy committed
85 86 87
	s.incoming <- blkRecv{from: from, blk: blk}
}

Jeromy's avatar
Jeromy committed
88
func (s *Session) interestedIn(c *cid.Cid) bool {
Jeromy's avatar
Jeromy committed
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
	return s.interest.Contains(c.KeyString())
}

const provSearchDelay = time.Second * 10

func (s *Session) addActivePeer(p peer.ID) {
	if _, ok := s.activePeers[p]; !ok {
		s.activePeers[p] = struct{}{}
		s.activePeersArr = append(s.activePeersArr, p)
	}
}

func (s *Session) resetTick() {
	if s.latTotal == 0 {
		s.tick.Reset(provSearchDelay)
	} else {
		avLat := s.latTotal / time.Duration(s.fetchcnt)
		s.tick.Reset(s.baseTickDelay + (3 * avLat))
	}
}

func (s *Session) run(ctx context.Context) {
	s.tick = time.NewTimer(provSearchDelay)
	newpeers := make(chan peer.ID, 16)
	for {
		select {
		case blk := <-s.incoming:
			s.tick.Stop()

			s.addActivePeer(blk.from)

			s.receiveBlock(ctx, blk.blk)

			s.resetTick()
		case keys := <-s.newReqs:
			for _, k := range keys {
				s.interest.Add(k.KeyString(), nil)
			}
			if s.liveCnt < activeWantsLimit {
				toadd := activeWantsLimit - s.liveCnt
				if toadd > len(keys) {
					toadd = len(keys)
				}
				s.liveCnt += toadd

				now := keys[:toadd]
				keys = keys[toadd:]

				s.wantBlocks(ctx, now)
			}
			s.tofetch = append(s.tofetch, keys...)
		case keys := <-s.cancelKeys:
			s.cancel(keys)

		case <-s.tick.C:
			var live []*cid.Cid
Jeromy's avatar
Jeromy committed
145
			for c := range s.liveWants {
Jeromy's avatar
Jeromy committed
146 147 148 149 150 151
				cs, _ := cid.Cast([]byte(c))
				live = append(live, cs)
				s.liveWants[c] = time.Now()
			}

			// Broadcast these keys to everyone we're connected to
Jeromy's avatar
Jeromy committed
152
			s.bs.wm.WantBlocks(ctx, live, nil, s.id)
Jeromy's avatar
Jeromy committed
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191

			if len(live) > 0 {
				go func() {
					for p := range s.bs.network.FindProvidersAsync(ctx, live[0], 10) {
						newpeers <- p
					}
				}()
			}
			s.resetTick()
		case p := <-newpeers:
			s.addActivePeer(p)
		case <-ctx.Done():
			return
		}
	}
}

func (s *Session) receiveBlock(ctx context.Context, blk blocks.Block) {
	ks := blk.Cid().KeyString()
	if _, ok := s.liveWants[ks]; ok {
		s.liveCnt--
		tval := s.liveWants[ks]
		s.latTotal += time.Since(tval)
		s.fetchcnt++
		delete(s.liveWants, ks)
		s.notif.Publish(blk)

		if len(s.tofetch) > 0 {
			next := s.tofetch[0:1]
			s.tofetch = s.tofetch[1:]
			s.wantBlocks(ctx, next)
		}
	}
}

func (s *Session) wantBlocks(ctx context.Context, ks []*cid.Cid) {
	for _, c := range ks {
		s.liveWants[c.KeyString()] = time.Now()
	}
Jeromy's avatar
Jeromy committed
192
	s.bs.wm.WantBlocks(ctx, ks, s.activePeersArr, s.id)
Jeromy's avatar
Jeromy committed
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
}

func (s *Session) cancel(keys []*cid.Cid) {
	sset := cid.NewSet()
	for _, c := range keys {
		sset.Add(c)
	}
	var i, j int
	for ; j < len(s.tofetch); j++ {
		if sset.Has(s.tofetch[j]) {
			continue
		}
		s.tofetch[i] = s.tofetch[j]
		i++
	}
	s.tofetch = s.tofetch[:i]
}

func (s *Session) cancelWants(keys []*cid.Cid) {
	s.cancelKeys <- keys
}

func (s *Session) fetch(ctx context.Context, keys []*cid.Cid) {
	select {
	case s.newReqs <- keys:
	case <-ctx.Done():
	}
}

Jeromy's avatar
Jeromy committed
222 223 224
// GetBlocks fetches a set of blocks within the context of this session and
// returns a channel that found blocks will be returned on. No order is
// guaranteed on the returned blocks.
Jeromy's avatar
Jeromy committed
225 226 227 228 229
func (s *Session) GetBlocks(ctx context.Context, keys []*cid.Cid) (<-chan blocks.Block, error) {
	ctx = logging.ContextWithLoggable(ctx, s.uuid)
	return getBlocksImpl(ctx, keys, s.notif, s.fetch, s.cancelWants)
}

Jeromy's avatar
Jeromy committed
230
// GetBlock fetches a single block
Jeromy's avatar
Jeromy committed
231 232 233
func (s *Session) GetBlock(parent context.Context, k *cid.Cid) (blocks.Block, error) {
	return getBlock(parent, k, s.GetBlocks)
}