bitswap.go 4.61 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
func (bs *bitswap) Block(ctx context.Context, k u.Key) (*blocks.Block, error) {
67

68
	provs_ch := bs.routing.FindProvidersAsync(ctx, k, 20)
69

70
	blockChannel := make(chan blocks.Block)
71

72
	// TODO: when the data is received, shut down this for loop ASAP
73 74 75
	go func() {
		for p := range provs_ch {
			go func(pr *peer.Peer) {
76
				blk, err := bs.getBlock(ctx, k, pr)
77 78 79 80
				if err != nil {
					return
				}
				select {
81
				case blockChannel <- *blk:
82 83 84 85 86
				default:
				}
			}(p)
		}
	}()
87 88

	select {
89 90
	case block := <-blockChannel:
		close(blockChannel)
91
		return &block, nil
92 93
	case <-ctx.Done():
		return nil, ctx.Err()
94
	}
95 96
}

97
func (bs *bitswap) getBlock(ctx context.Context, k u.Key, p *peer.Peer) (*blocks.Block, error) {
98

99 100
	blockChannel := bs.notifications.Subscribe(ctx, k)

101
	message := bsmsg.New()
102
	message.AppendWanted(k)
103

104
	bs.send(ctx, p, message)
105

106 107
	block, ok := <-blockChannel
	if !ok {
108 109
		return nil, u.ErrTimeout
	}
110
	return &block, nil
111 112
}

113
func (bs *bitswap) sendToPeersThatWant(ctx context.Context, block blocks.Block) {
114 115 116
	for _, p := range bs.strategy.Peers() {
		if bs.strategy.BlockIsWantedByPeer(block.Key(), p) {
			if bs.strategy.ShouldSendBlockToPeer(block.Key(), p) {
117 118 119
				message := bsmsg.New()
				message.AppendBlock(block)
				go bs.send(ctx, p, message)
120 121 122 123 124
			}
		}
	}
}

125
// HasBlock announces the existance of a block to bitswap, potentially sending
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
126
// it to peers (Partners) whose WantLists include it.
127
func (bs *bitswap) HasBlock(ctx context.Context, blk blocks.Block) error {
128
	go bs.sendToPeersThatWant(ctx, blk)
129 130 131
	return bs.routing.Provide(blk.Key())
}

132
// TODO(brian): handle errors
133
func (bs *bitswap) ReceiveMessage(
134
	ctx context.Context, p *peer.Peer, incoming bsmsg.BitSwapMessage) (
135
	*peer.Peer, bsmsg.BitSwapMessage, error) {
136

137
	bs.strategy.MessageReceived(p, incoming)
138

139 140
	if incoming.Blocks() != nil {
		for _, block := range incoming.Blocks() {
141 142
			go bs.blockstore.Put(block) // FIXME(brian): err ignored
			go bs.notifications.Publish(block)
143 144 145 146
		}
	}

	if incoming.Wantlist() != nil {
147
		for _, key := range incoming.Wantlist() {
148
			if bs.strategy.ShouldSendBlockToPeer(key, p) {
149 150 151 152 153
				block, errBlockNotFound := bs.blockstore.Get(key)
				if errBlockNotFound != nil {
					// TODO(brian): log/return the error
					continue
				}
154 155 156
				message := bsmsg.New()
				message.AppendBlock(*block)
				go bs.send(ctx, p, message)
157
			}
158 159
		}
	}
160
	return nil, nil, nil
161
}
162

163 164 165
// 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
166
	bs.sender.SendMessage(ctx, p, m)
167
	bs.strategy.MessageSent(p, m)
168 169
}

170 171 172
func numBytes(b blocks.Block) int {
	return len(b.Data)
}