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

import (
4
	"errors"
Brian Tiger Chow's avatar
Brian Tiger Chow committed
5 6
	"time"

7
	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
8 9
	ds "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/datastore.go"

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

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

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

31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
// NewSession initializes a bitswap session.
func NewSession(parent context.Context, s bsnet.NetworkService, p *peer.Peer, d ds.Datastore, directory Routing) exchange.Interface {

	// FIXME(brian): instantiate a concrete Strategist
	receiver := bsnet.Forwarder{}
	bs := &bitswap{
		blockstore:    blockstore.NewBlockstore(d),
		notifications: notifications.New(),
		strategy:      strategy.New(),
		routing:       directory,
		sender:        bsnet.NewNetworkAdapter(s, &receiver),
	}
	receiver.Delegate(bs)

	return bs
}

48 49
// bitswap instances implement the bitswap protocol.
type bitswap struct {
50

51
	// sender delivers messages on behalf of the session
52
	sender bsnet.NetworkAdapter
53

54
	// blockstore is the local database
55
	// NB: ensure threadsafety
56
	blockstore blockstore.Blockstore
57

58
	// routing interface for communication
59
	routing Routing
60

61
	notifications notifications.PubSub
62

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

// GetBlock attempts to retrieve a particular block from peers, within timeout.
70
func (bs *bitswap) Block(k u.Key, timeout time.Duration) (
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
71
	*blocks.Block, error) {
72 73 74
	ctx, _ := context.WithTimeout(context.Background(), timeout)

	// TODO replace timeout with ctx in routing interface
75
	begin := time.Now()
76
	tleft := timeout - time.Now().Sub(begin)
77
	provs_ch := bs.routing.FindProvidersAsync(ctx, k, 20)
78

79
	blockChannel := make(chan blocks.Block)
80
	after := time.After(tleft)
81

82
	// TODO: when the data is received, shut down this for loop ASAP
83 84 85
	go func() {
		for p := range provs_ch {
			go func(pr *peer.Peer) {
86
				blk, err := bs.getBlock(ctx, k, pr)
87 88 89 90
				if err != nil {
					return
				}
				select {
91
				case blockChannel <- *blk:
92 93 94 95 96
				default:
				}
			}(p)
		}
	}()
97 98

	select {
99 100
	case block := <-blockChannel:
		close(blockChannel)
101
		return &block, nil
102 103
	case <-after:
		return nil, u.ErrTimeout
104
	}
105 106
}

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

109 110
	blockChannel := bs.notifications.Subscribe(ctx, k)

111
	message := bsmsg.New()
112
	message.AppendWanted(k)
113

114
	bs.send(ctx, p, message)
115

116 117
	block, ok := <-blockChannel
	if !ok {
118 119
		return nil, u.ErrTimeout
	}
120
	return &block, nil
121 122
}

123
func (bs *bitswap) sendToPeersThatWant(ctx context.Context, block blocks.Block) {
124 125 126
	for _, p := range bs.strategy.Peers() {
		if bs.strategy.BlockIsWantedByPeer(block.Key(), p) {
			if bs.strategy.ShouldSendBlockToPeer(block.Key(), p) {
127 128 129
				message := bsmsg.New()
				message.AppendBlock(block)
				go bs.send(ctx, p, message)
130 131 132 133 134
			}
		}
	}
}

135
// HasBlock announces the existance of a block to bitswap, potentially sending
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
136
// it to peers (Partners) whose WantLists include it.
137
func (bs *bitswap) HasBlock(blk blocks.Block) error {
138 139
	ctx := context.TODO()
	go bs.sendToPeersThatWant(ctx, blk)
140 141 142
	return bs.routing.Provide(blk.Key())
}

143
// TODO(brian): handle errors
144
func (bs *bitswap) ReceiveMessage(
145
	ctx context.Context, p *peer.Peer, incoming bsmsg.BitSwapMessage) (
146
	*peer.Peer, bsmsg.BitSwapMessage, error) {
147

148
	bs.strategy.MessageReceived(p, incoming)
149

150 151
	if incoming.Blocks() != nil {
		for _, block := range incoming.Blocks() {
152 153
			go bs.blockstore.Put(block) // FIXME(brian): err ignored
			go bs.notifications.Publish(block)
154 155 156 157
		}
	}

	if incoming.Wantlist() != nil {
158
		for _, key := range incoming.Wantlist() {
159
			if bs.strategy.ShouldSendBlockToPeer(key, p) {
160 161 162 163 164
				block, errBlockNotFound := bs.blockstore.Get(key)
				if errBlockNotFound != nil {
					// TODO(brian): log/return the error
					continue
				}
165 166 167
				message := bsmsg.New()
				message.AppendBlock(*block)
				go bs.send(ctx, p, message)
168
			}
169 170
		}
	}
171 172
	return nil, nil, errors.New("TODO implement")
}
173

174 175 176 177 178
// 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) {
	bs.sender.SendMessage(context.Background(), p, m)
	bs.strategy.MessageSent(p, m)
179 180
}

181 182 183
func numBytes(b blocks.Block) int {
	return len(b.Data)
}