bitswap.go 4.95 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
package bitswap

import (
	"errors"
	"time"

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

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

	// 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 50 51 52 53 54 55 56 57 58
// bitswap instances implement the bitswap protocol.
type bitswap struct {

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

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

	// routing interface for communication
59
	routing Routing
60 61 62 63 64 65 66 67 68 69 70 71

	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
}

// GetBlock attempts to retrieve a particular block from peers, within timeout.
func (bs *bitswap) Block(k u.Key, timeout time.Duration) (
	*blocks.Block, error) {
72 73 74
	ctx, _ := context.WithTimeout(context.Background(), timeout)

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

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

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

	select {
	case block := <-blockChannel:
		close(blockChannel)
		return &block, nil
	case <-after:
		return nil, u.ErrTimeout
	}
}

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

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

	message := bsmsg.New()
	message.AppendWanted(k)

114
	bs.send(ctx, p, message)
115 116 117 118 119 120 121 122

	block, ok := <-blockChannel
	if !ok {
		return nil, u.ErrTimeout
	}
	return &block, nil
}

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 136 137
			}
		}
	}
}

// HasBlock announces the existance of a block to bitswap, potentially sending
// it to peers (Partners) whose WantLists include it.
func (bs *bitswap) HasBlock(blk blocks.Block) error {
138 139
	ctx := context.TODO()
	go bs.sendToPeersThatWant(ctx, blk)
140 141 142 143 144
	return bs.routing.Provide(blk.Key())
}

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

148
	bs.strategy.MessageReceived(p, incoming)
149 150 151 152 153 154 155 156 157 158

	if incoming.Blocks() != nil {
		for _, block := range incoming.Blocks() {
			go bs.blockstore.Put(block) // FIXME(brian): err ignored
			go bs.notifications.Publish(block)
		}
	}

	if incoming.Wantlist() != nil {
		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 173
			}
		}
	}
	return nil, nil, errors.New("TODO implement")
}

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