service.go 4.51 KB
Newer Older
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1 2 3 4 5 6 7 8 9
package service

import (
	"errors"
	"sync"

	msg "github.com/jbenet/go-ipfs/net/message"
	u "github.com/jbenet/go-ipfs/util"

10
	context "github.com/jbenet/go-ipfs/Godeps/_workspace/src/code.google.com/p/go.net/context"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
11 12 13 14 15 16 17 18
)

// Handler is an interface that objects must implement in order to handle
// a service's requests.
type Handler interface {

	// HandleMessage receives an incoming message, and potentially returns
	// a response message to send back.
19
	HandleMessage(context.Context, msg.NetMessage) (msg.NetMessage, error)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
}

// Service is a networking component that protocols can use to multiplex
// messages over the same channel, and to issue + handle requests.
type Service struct {
	// Handler is the object registered to handle incoming requests.
	Handler Handler

	// Requests are all the pending requests on this service.
	Requests     RequestMap
	RequestsLock sync.RWMutex

	// cancel is the function to stop the Service
	cancel context.CancelFunc

	// Message Pipe (connected to the outside world)
	*msg.Pipe
}

// NewService creates a service object with given type ID and Handler
40 41
func NewService(h Handler) *Service {
	return &Service{
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
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
		Handler:  h,
		Requests: RequestMap{},
		Pipe:     msg.NewPipe(10),
	}
}

// Start kicks off the Service goroutines.
func (s *Service) Start(ctx context.Context) error {
	if s.cancel != nil {
		return errors.New("Service already started.")
	}

	// make a cancellable context.
	ctx, s.cancel = context.WithCancel(ctx)

	go s.handleIncomingMessages(ctx)
	return nil
}

// Stop stops Service activity.
func (s *Service) Stop() {
	s.cancel()
	s.cancel = context.CancelFunc(nil)
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
67 68 69 70 71
// GetPipe implements the mux.Protocol interface
func (s *Service) GetPipe() *msg.Pipe {
	return s.Pipe
}

72 73
// sendMessage sends a message out (actual leg work. SendMessage is to export w/o rid)
func (s *Service) sendMessage(ctx context.Context, m msg.NetMessage, rid RequestID) error {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
74 75

	// serialize ServiceMessage wrapper
76
	data, err := wrapData(m.Data(), rid)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
77 78 79 80 81
	if err != nil {
		return err
	}

	// send message
82
	m2 := msg.New(m.Peer(), data)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
83 84 85 86 87 88 89 90 91
	select {
	case s.Outgoing <- m2:
	case <-ctx.Done():
		return ctx.Err()
	}

	return nil
}

92 93 94 95 96
// SendMessage sends a message out
func (s *Service) SendMessage(ctx context.Context, m msg.NetMessage) error {
	return s.sendMessage(ctx, m, nil)
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
97
// SendRequest sends a request message out and awaits a response.
98
func (s *Service) SendRequest(ctx context.Context, m msg.NetMessage) (msg.NetMessage, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
99 100

	// create a request
101
	r, err := NewRequest(m.Peer().ID)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
	if err != nil {
		return nil, err
	}

	// register Request
	s.RequestsLock.Lock()
	s.Requests[r.Key()] = r
	s.RequestsLock.Unlock()

	// defer deleting this request
	defer func() {
		s.RequestsLock.Lock()
		delete(s.Requests, r.Key())
		s.RequestsLock.Unlock()
	}()

	// check if we should bail after waiting for mutex
	select {
	default:
	case <-ctx.Done():
		return nil, ctx.Err()
	}

	// Send message
126
	s.sendMessage(ctx, m, r.ID)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153

	// wait for response
	m = nil
	err = nil
	select {
	case m = <-r.Response:
	case <-ctx.Done():
		err = ctx.Err()
	}

	return m, err
}

// handleIncoming consumes the messages on the s.Incoming channel and
// routes them appropriately (to requests, or handler).
func (s *Service) handleIncomingMessages(ctx context.Context) {
	for {
		select {
		case m := <-s.Incoming:
			go s.handleIncomingMessage(ctx, m)

		case <-ctx.Done():
			return
		}
	}
}

154
func (s *Service) handleIncomingMessage(ctx context.Context, m msg.NetMessage) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
155 156

	// unwrap the incoming message
157
	data, rid, err := unwrapData(m.Data())
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
158 159 160
	if err != nil {
		u.PErr("de-serializing error: %v\n", err)
	}
161
	m2 := msg.New(m.Peer(), data)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
162 163 164

	// if it's a request (or has no RequestID), handle it
	if rid == nil || rid.IsRequest() {
165 166 167 168 169
		if s.Handler == nil {
			u.PErr("service dropped msg: %v\n", m)
			return // no handler, drop it.
		}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
170 171 172 173 174 175 176 177
		r1, err := s.Handler.HandleMessage(ctx, m2)
		if err != nil {
			u.PErr("handled message yielded error %v\n", err)
			return
		}

		// if handler gave us a response, send it back out!
		if r1 != nil {
178
			err := s.sendMessage(ctx, r1, rid.Response())
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
179 180 181 182 183 184 185 186 187 188 189 190
			if err != nil {
				u.PErr("error sending response message: %v\n", err)
			}
		}
		return
	}

	// Otherwise, it is a response. handle it.
	if !rid.IsResponse() {
		u.PErr("RequestID should identify a response here.\n")
	}

191
	key := RequestKey(m.Peer().ID, RequestID(rid))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
192 193 194 195 196 197 198 199 200 201 202 203 204 205
	s.RequestsLock.RLock()
	r, found := s.Requests[key]
	s.RequestsLock.RUnlock()

	if !found {
		u.PErr("no request key %v (timeout?)\n", []byte(key))
		return
	}

	select {
	case r.Response <- m2:
	case <-ctx.Done():
	}
}