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

import (
4
	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
5 6
	ds "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/datastore.go"

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
7
	blocks "github.com/jbenet/go-ipfs/blocks"
8
	blockstore "github.com/jbenet/go-ipfs/blockstore"
9 10 11 12 13
	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"
14
	peer "github.com/jbenet/go-ipfs/peer"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
15
	u "github.com/jbenet/go-ipfs/util"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
16 17
)

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

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

27 28 29
// NewSession initializes a bitswap session.
func NewSession(parent context.Context, s bsnet.NetworkService, p *peer.Peer, d ds.Datastore, directory Routing) exchange.Interface {

30
	adapter := bsnet.NewNetworkAdapter(s, nil)
31 32 33 34 35
	bs := &bitswap{
		blockstore:    blockstore.NewBlockstore(d),
		notifications: notifications.New(),
		strategy:      strategy.New(),
		routing:       directory,
36
		sender:        adapter,
37
	}
38
	adapter.SetDelegate(bs)
39 40 41 42

	return bs
}

43 44
// bitswap instances implement the bitswap protocol.
type bitswap struct {
45

46
	// sender delivers messages on behalf of the session
47
	sender bsnet.NetworkAdapter
48

49
	// blockstore is the local database
50
	// NB: ensure threadsafety
51
	blockstore blockstore.Blockstore
52

53
	// routing interface for communication
54
	routing Routing
55

56
	notifications notifications.PubSub
57

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

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

70 71
	ctx, cancelFunc := context.WithCancel(parent)
	promise := bs.notifications.Subscribe(ctx, k)
72

73
	go func() {
74 75 76 77 78 79 80
		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)
81 82 83
				if err != nil {
					return
				}
84 85 86 87 88 89 90
				// 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)

				bs.ReceiveMessage(ctx, p, response)
			}(i)
91 92
		}
	}()
93 94

	select {
95 96
	case block := <-promise:
		cancelFunc()
97
		return &block, nil
98 99
	case <-parent.Done():
		return nil, parent.Err()
100 101 102
	}
}

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

110
// TODO(brian): handle errors
111
func (bs *bitswap) ReceiveMessage(
112
	ctx context.Context, p *peer.Peer, incoming bsmsg.BitSwapMessage) (
113
	*peer.Peer, bsmsg.BitSwapMessage, error) {
114

115
	bs.strategy.MessageReceived(p, incoming)
116

117 118
	if incoming.Blocks() != nil {
		for _, block := range incoming.Blocks() {
119 120
			go bs.blockstore.Put(block) // FIXME(brian): err ignored
			go bs.notifications.Publish(block)
121 122 123 124
		}
	}

	if incoming.Wantlist() != nil {
125
		for _, key := range incoming.Wantlist() {
126
			if bs.strategy.ShouldSendBlockToPeer(key, p) {
127 128 129 130 131
				block, errBlockNotFound := bs.blockstore.Get(key)
				if errBlockNotFound != nil {
					// TODO(brian): log/return the error
					continue
				}
132 133 134
				message := bsmsg.New()
				message.AppendBlock(*block)
				go bs.send(ctx, p, message)
135
			}
136 137
		}
	}
138
	return nil, nil, nil
139
}
140

141 142 143
// 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
144
	bs.sender.SendMessage(ctx, p, m)
145
	bs.strategy.MessageSent(p, m)
146 147
}

148 149 150
func numBytes(b blocks.Block) int {
	return len(b.Data)
}
151 152 153 154 155 156 157 158 159 160 161 162

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)
			}
		}
	}
}