net_message_adapter.go 2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
package network

import (
	context "github.com/jbenet/go-ipfs/Godeps/_workspace/src/code.google.com/p/go.net/context"

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

11 12 13 14 15
// NetMessageAdapter wraps a NetMessage network service
func NetMessageAdapter(s NetMessageService, r Receiver) Adapter {
	adapter := impl{
		nms:      s,
		receiver: r,
16 17 18 19 20
	}
	s.SetHandler(&adapter)
	return &adapter
}

21 22 23 24 25 26
// implements an Adapter that integrates with a NetMessage network service
type impl struct {
	nms NetMessageService

	// inbound messages from the network are forwarded to the receiver
	receiver Receiver
27 28 29 30
}

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

	if adapter.receiver == nil {
35
		return nil, nil
36 37 38 39
	}

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

44
	p, bsmsg := adapter.receiver.ReceiveMessage(ctx, incoming.Peer(), received)
45 46 47 48 49 50 51 52

	// TODO(brian): put this in a helper function
	if bsmsg == nil || p == nil {
		return nil, nil
	}

	outgoing, err := bsmsg.ToNet(p)
	if err != nil {
53 54
		adapter.receiver.ReceiveError(err)
		return nil, nil
55 56 57 58 59
	}

	return outgoing, nil
}

60
func (adapter *impl) SendMessage(
61 62 63 64 65 66 67 68
	ctx context.Context,
	p *peer.Peer,
	outgoing bsmsg.BitSwapMessage) error {

	nmsg, err := outgoing.ToNet(p)
	if err != nil {
		return err
	}
69
	return adapter.nms.SendMessage(ctx, nmsg)
70 71
}

72
func (adapter *impl) SendRequest(
73 74 75 76 77 78 79 80
	ctx context.Context,
	p *peer.Peer,
	outgoing bsmsg.BitSwapMessage) (bsmsg.BitSwapMessage, error) {

	outgoingMsg, err := outgoing.ToNet(p)
	if err != nil {
		return nil, err
	}
81
	incomingMsg, err := adapter.nms.SendRequest(ctx, outgoingMsg)
82 83 84 85 86 87
	if err != nil {
		return nil, err
	}
	return bsmsg.FromNet(incomingMsg)
}

88
func (adapter *impl) SetDelegate(r Receiver) {
89 90
	adapter.receiver = r
}