network_adapter.go 2.13 KB
Newer Older
1
package network
2 3

import (
4 5
	"errors"

6 7 8 9 10 11 12
	context "github.com/jbenet/go-ipfs/Godeps/_workspace/src/code.google.com/p/go.net/context"

	bsmsg "github.com/jbenet/go-ipfs/bitswap/message"
	netmsg "github.com/jbenet/go-ipfs/net/message"
	peer "github.com/jbenet/go-ipfs/peer"
)

13
// NewSender wraps a network Service to perform translation between
14 15
// BitSwapMessage and NetMessage formats. This allows the BitSwap session to
// ignore these details.
16 17 18 19 20 21 22
func NewNetworkAdapter(s NetworkService, r Receiver) NetworkAdapter {
	adapter := networkAdapter{
		networkService: s,
		receiver:       r,
	}
	s.SetHandler(&adapter)
	return &adapter
23 24
}

25 26 27 28
// networkAdapter implements NetworkAdapter
type networkAdapter struct {
	networkService NetworkService
	receiver       Receiver
29 30 31 32
}

// HandleMessage marshals and unmarshals net messages, forwarding them to the
// BitSwapMessage receiver
33
func (adapter *networkAdapter) HandleMessage(
34 35
	ctx context.Context, incoming netmsg.NetMessage) (netmsg.NetMessage, error) {

36 37 38 39
	if adapter.receiver == nil {
		return nil, errors.New("No receiver. NetMessage dropped")
	}

40 41 42 43 44
	received, err := bsmsg.FromNet(incoming)
	if err != nil {
		return nil, err
	}

45
	p, bsmsg, err := adapter.receiver.ReceiveMessage(ctx, incoming.Peer(), received)
46 47 48
	if err != nil {
		return nil, err
	}
49 50 51

	// TODO(brian): put this in a helper function
	if bsmsg == nil || p == nil {
52 53 54 55 56 57 58 59 60 61 62
		return nil, nil
	}

	outgoing, err := bsmsg.ToNet(p)
	if err != nil {
		return nil, err
	}

	return outgoing, nil
}

63 64 65 66
func (adapter *networkAdapter) SendMessage(
	ctx context.Context,
	p *peer.Peer,
	outgoing bsmsg.BitSwapMessage) error {
67 68 69 70 71

	nmsg, err := outgoing.ToNet(p)
	if err != nil {
		return err
	}
72
	return adapter.networkService.SendMessage(ctx, nmsg)
73 74
}

75 76 77 78
func (adapter *networkAdapter) SendRequest(
	ctx context.Context,
	p *peer.Peer,
	outgoing bsmsg.BitSwapMessage) (bsmsg.BitSwapMessage, error) {
79 80 81 82 83

	outgoingMsg, err := outgoing.ToNet(p)
	if err != nil {
		return nil, err
	}
84
	incomingMsg, err := adapter.networkService.SendRequest(ctx, outgoingMsg)
85 86 87 88 89
	if err != nil {
		return nil, err
	}
	return bsmsg.FromNet(incomingMsg)
}
90 91 92 93

func (adapter *networkAdapter) SetDelegate(r Receiver) {
	adapter.receiver = r
}