service_wrapper.go 1.9 KB
Newer Older
1
package transmission
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33

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"
	netmsg "github.com/jbenet/go-ipfs/net/message"
	netservice "github.com/jbenet/go-ipfs/net/service"
	peer "github.com/jbenet/go-ipfs/peer"
)

func NewBSNetService(ctx context.Context, r Receiver) Sender {
	h := &handlerWrapper{r}
	s := netservice.NewService(ctx, h)
	return &serviceWrapper{*s}
}

// handlerWrapper is responsible for marshaling/unmarshaling NetMessages. It
// 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
	}

34
	bsmsg, p, err := wrapper.bitswapDelegate.ReceiveMessage(ctx, incoming.Peer(), received)
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
	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
}

type serviceWrapper struct {
	serviceDelegate netservice.Service
}

func (wrapper *serviceWrapper) SendMessage(
	ctx context.Context, p *peer.Peer, outgoing bsmsg.Exportable) error {
	nmsg, err := outgoing.ToNet(p)
	if err != nil {
		return err
	}
	req, err := netservice.NewRequest(p.ID)
	return wrapper.serviceDelegate.SendMessage(ctx, nmsg, req.ID)
}

func (wrapper *serviceWrapper) SendRequest(ctx context.Context,
	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)
}