bitswap.go 4.69 KB
Newer Older
1 2 3
package bitswap

import (
4 5
	"errors"

6 7 8 9 10 11 12 13 14 15 16 17 18 19
	context "github.com/jbenet/go-ipfs/Godeps/_workspace/src/code.google.com/p/go.net/context"
	ds "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/datastore.go"

	blocks "github.com/jbenet/go-ipfs/blocks"
	blockstore "github.com/jbenet/go-ipfs/blockstore"
	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"
	peer "github.com/jbenet/go-ipfs/peer"
	u "github.com/jbenet/go-ipfs/util"
)

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

24
	networkAdapter := bsnet.NetMessageAdapter(s, nil)
25 26 27 28 29
	bs := &bitswap{
		blockstore:    blockstore.NewBlockstore(d),
		notifications: notifications.New(),
		strategy:      strategy.New(),
		routing:       directory,
30
		sender:        networkAdapter,
31
	}
32
	networkAdapter.SetDelegate(bs)
33 34 35 36

	return bs
}

37 38 39 40
// bitswap instances implement the bitswap protocol.
type bitswap struct {

	// sender delivers messages on behalf of the session
41
	sender bsnet.Adapter
42 43 44 45 46 47

	// blockstore is the local database
	// NB: ensure threadsafety
	blockstore blockstore.Blockstore

	// routing interface for communication
48
	routing bsnet.Routing
49 50 51 52 53 54 55 56 57

	notifications notifications.PubSub

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

58 59
// GetBlock attempts to retrieve a particular block from peers within the
// deadline enforced by the context
60 61
//
// TODO ensure only one active request per key
62
func (bs *bitswap) Block(parent context.Context, k u.Key) (*blocks.Block, error) {
63

64 65
	ctx, cancelFunc := context.WithCancel(parent)
	promise := bs.notifications.Subscribe(ctx, k)
66 67

	go func() {
68 69 70 71 72
		const maxProviders = 20
		peersToQuery := bs.routing.FindProvidersAsync(ctx, k, maxProviders)
		message := bsmsg.New()
		message.AppendWanted(k)
		for i := range peersToQuery {
73
			func(p *peer.Peer) {
74
				response, err := bs.sender.SendRequest(ctx, p, message)
75 76 77
				if err != nil {
					return
				}
78 79 80 81 82
				// 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)

83 84 85
				if response == nil {
					return
				}
86 87
				bs.ReceiveMessage(ctx, p, response)
			}(i)
88 89 90 91
		}
	}()

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

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

// TODO(brian): handle errors
func (bs *bitswap) ReceiveMessage(
109
	ctx context.Context, p *peer.Peer, incoming bsmsg.BitSwapMessage) (
110
	*peer.Peer, bsmsg.BitSwapMessage, error) {
111 112 113 114 115 116
	if p == nil {
		return nil, nil, errors.New("Received nil Peer")
	}
	if incoming == nil {
		return nil, nil, errors.New("Received nil Message")
	}
117

118
	bs.strategy.MessageReceived(p, incoming)
119

120 121 122 123 124 125 126 127 128
	for _, block := range incoming.Blocks() {
		err := bs.blockstore.Put(block) // FIXME(brian): err ignored
		if err != nil {
			return nil, nil, err
		}
		bs.notifications.Publish(block)
		err = bs.HasBlock(ctx, block) // FIXME err ignored
		if err != nil {
			return nil, nil, err
129 130 131
		}
	}

132 133 134 135 136
	for _, key := range incoming.Wantlist() {
		if bs.strategy.ShouldSendBlockToPeer(key, p) {
			block, errBlockNotFound := bs.blockstore.Get(key)
			if errBlockNotFound != nil {
				return nil, nil, errBlockNotFound
137
			}
138 139 140 141
			message := bsmsg.New()
			message.AppendBlock(*block)
			defer bs.strategy.MessageSent(p, message)
			return p, message, nil
142 143
		}
	}
144
	return nil, nil, nil
145 146
}

147 148 149
// 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
150
	bs.sender.SendMessage(ctx, p, m)
151
	bs.strategy.MessageSent(p, m)
152 153
}

154 155 156 157 158 159
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)
160
				bs.send(ctx, p, message)
161 162 163 164
			}
		}
	}
}