bitswap.go 4.97 KB
Newer Older
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1 2 3
package bitswap

import (
4 5
	"errors"

6
	context "github.com/jbenet/go-ipfs/Godeps/_workspace/src/code.google.com/p/go.net/context"
Brian Tiger Chow's avatar
Brian Tiger Chow committed
7 8
	ds "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/datastore.go"

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
9
	blocks "github.com/jbenet/go-ipfs/blocks"
10
	blockstore "github.com/jbenet/go-ipfs/blockstore"
11 12 13 14 15
	exchange "github.com/jbenet/go-ipfs/exchange"
	bsmsg "github.com/jbenet/go-ipfs/exchange/bitswap/message"
	bsnet "github.com/jbenet/go-ipfs/exchange/bitswap/network"
	notifications "github.com/jbenet/go-ipfs/exchange/bitswap/notifications"
	strategy "github.com/jbenet/go-ipfs/exchange/bitswap/strategy"
16
	peer "github.com/jbenet/go-ipfs/peer"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
17
	u "github.com/jbenet/go-ipfs/util"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
18 19
)

20 21 22
// TODO rename -> Router?
type Routing interface {
	// FindProvidersAsync returns a channel of providers for the given key
23
	FindProvidersAsync(context.Context, u.Key, int) <-chan *peer.Peer
24 25 26 27 28

	// Provide provides the key to the network
	Provide(key u.Key) error
}

29 30 31
// NetMessageSession initializes a BitSwap session that communicates over the
// provided NetMessage service
func NetMessageSession(parent context.Context, s bsnet.NetMessageService, p *peer.Peer, d ds.Datastore, directory Routing) exchange.Interface {
32

33
	networkAdapter := bsnet.NetMessageAdapter(s, nil)
34 35 36 37 38
	bs := &bitswap{
		blockstore:    blockstore.NewBlockstore(d),
		notifications: notifications.New(),
		strategy:      strategy.New(),
		routing:       directory,
39
		sender:        networkAdapter,
40
	}
41
	networkAdapter.SetDelegate(bs)
42 43 44 45

	return bs
}

46 47
// bitswap instances implement the bitswap protocol.
type bitswap struct {
48

49
	// sender delivers messages on behalf of the session
50
	sender bsnet.Adapter
51

52
	// blockstore is the local database
53
	// NB: ensure threadsafety
54
	blockstore blockstore.Blockstore
55

56
	// routing interface for communication
57
	routing Routing
58

59
	notifications notifications.PubSub
60

61
	// strategy listens to network traffic and makes decisions about how to
62
	// interact with partners.
63 64
	// TODO(brian): save the strategy's state to the datastore
	strategy strategy.Strategy
65 66
}

67 68
// GetBlock attempts to retrieve a particular block from peers within the
// deadline enforced by the context
69 70
//
// TODO ensure only one active request per key
71
func (bs *bitswap) Block(parent context.Context, k u.Key) (*blocks.Block, error) {
72

73 74
	ctx, cancelFunc := context.WithCancel(parent)
	promise := bs.notifications.Subscribe(ctx, k)
75

76
	go func() {
77 78 79 80 81 82 83
		const maxProviders = 20
		peersToQuery := bs.routing.FindProvidersAsync(ctx, k, maxProviders)
		message := bsmsg.New()
		message.AppendWanted(k)
		for i := range peersToQuery {
			go func(p *peer.Peer) {
				response, err := bs.sender.SendRequest(ctx, p, message)
84 85 86
				if err != nil {
					return
				}
87 88 89 90 91
				// FIXME ensure accounting is handled correctly when
				// communication fails. May require slightly different API to
				// get better guarantees. May need shared sequence numbers.
				bs.strategy.MessageSent(p, message)

92 93 94
				if response == nil {
					return
				}
95 96
				bs.ReceiveMessage(ctx, p, response)
			}(i)
97 98
		}
	}()
99 100

	select {
101 102
	case block := <-promise:
		cancelFunc()
103
		return &block, nil
104 105
	case <-parent.Done():
		return nil, parent.Err()
106 107 108
	}
}

109
// HasBlock announces the existance of a block to bitswap, potentially sending
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
110
// it to peers (Partners) whose WantLists include it.
111
func (bs *bitswap) HasBlock(ctx context.Context, blk blocks.Block) error {
112
	go bs.sendToPeersThatWant(ctx, blk)
113 114 115
	return bs.routing.Provide(blk.Key())
}

116
// TODO(brian): handle errors
117
func (bs *bitswap) ReceiveMessage(
118
	ctx context.Context, p *peer.Peer, incoming bsmsg.BitSwapMessage) (
119
	*peer.Peer, bsmsg.BitSwapMessage, error) {
120 121 122 123 124 125
	if p == nil {
		return nil, nil, errors.New("Received nil Peer")
	}
	if incoming == nil {
		return nil, nil, errors.New("Received nil Message")
	}
126

127
	bs.strategy.MessageReceived(p, incoming)
128

129 130
	if incoming.Blocks() != nil {
		for _, block := range incoming.Blocks() {
131 132
			go bs.blockstore.Put(block) // FIXME(brian): err ignored
			go bs.notifications.Publish(block)
133
			go bs.HasBlock(ctx, block) // FIXME err ignored
134 135 136 137
		}
	}

	if incoming.Wantlist() != nil {
138
		for _, key := range incoming.Wantlist() {
139
			if bs.strategy.ShouldSendBlockToPeer(key, p) {
140 141 142 143 144
				block, errBlockNotFound := bs.blockstore.Get(key)
				if errBlockNotFound != nil {
					// TODO(brian): log/return the error
					continue
				}
145 146 147
				message := bsmsg.New()
				message.AppendBlock(*block)
				go bs.send(ctx, p, message)
148
			}
149 150
		}
	}
151
	return nil, nil, nil
152
}
153

154 155 156
// send strives to ensure that accounting is always performed when a message is
// sent
func (bs *bitswap) send(ctx context.Context, p *peer.Peer, m bsmsg.BitSwapMessage) {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
157
	bs.sender.SendMessage(ctx, p, m)
158
	bs.strategy.MessageSent(p, m)
159 160
}

161 162 163
func numBytes(b blocks.Block) int {
	return len(b.Data)
}
164 165 166 167 168 169 170 171 172 173 174 175

func (bs *bitswap) sendToPeersThatWant(ctx context.Context, block blocks.Block) {
	for _, p := range bs.strategy.Peers() {
		if bs.strategy.BlockIsWantedByPeer(block.Key(), p) {
			if bs.strategy.ShouldSendBlockToPeer(block.Key(), p) {
				message := bsmsg.New()
				message.AppendBlock(block)
				go bs.send(ctx, p, message)
			}
		}
	}
}