network_adapter.go 1.95 KB
Newer Older
1
package transmission
2 3 4 5 6

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

	bsmsg "github.com/jbenet/go-ipfs/bitswap/message"
7
	net "github.com/jbenet/go-ipfs/net"
8 9 10 11
	netmsg "github.com/jbenet/go-ipfs/net/message"
	peer "github.com/jbenet/go-ipfs/peer"
)

12 13 14 15
// NewSender wraps the net.service.Sender to perform translation between
// BitSwapMessage and NetMessage formats. This allows the BitSwap session to
// ignore these details.
func NewSender(s net.Sender) Sender {
16
	return &senderWrapper{s}
17 18
}

19 20
// handlerWrapper implements the net.service.Handler interface. It is
// responsible for converting between
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
// delegates calls to the BitSwap delegate.
type handlerWrapper struct {
	bitswapDelegate Receiver
}

// HandleMessage marshals and unmarshals net messages, forwarding them to the
// BitSwapMessage receiver
func (wrapper *handlerWrapper) HandleMessage(
	ctx context.Context, incoming netmsg.NetMessage) (netmsg.NetMessage, error) {

	received, err := bsmsg.FromNet(incoming)
	if err != nil {
		return nil, err
	}

36
	bsmsg, p, err := wrapper.bitswapDelegate.ReceiveMessage(ctx, incoming.Peer(), received)
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
	if err != nil {
		return nil, err
	}
	if bsmsg == nil {
		return nil, nil
	}

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

	return outgoing, nil
}

52
type senderWrapper struct {
53
	serviceDelegate net.Sender
54 55
}

56
func (wrapper *senderWrapper) SendMessage(
57 58 59 60 61
	ctx context.Context, p *peer.Peer, outgoing bsmsg.Exportable) error {
	nmsg, err := outgoing.ToNet(p)
	if err != nil {
		return err
	}
62
	return wrapper.serviceDelegate.SendMessage(ctx, nmsg)
63 64
}

65
func (wrapper *senderWrapper) SendRequest(ctx context.Context,
66 67 68 69 70 71 72 73 74 75 76 77
	p *peer.Peer, outgoing bsmsg.Exportable) (bsmsg.BitSwapMessage, error) {

	outgoingMsg, err := outgoing.ToNet(p)
	if err != nil {
		return nil, err
	}
	incomingMsg, err := wrapper.serviceDelegate.SendRequest(ctx, outgoingMsg)
	if err != nil {
		return nil, err
	}
	return bsmsg.FromNet(incomingMsg)
}