service.go 5.78 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
)

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
13 14
var log = u.Logger("service")

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
15 16 17 18
// ErrNoResponse is returned by Service when a Request did not get a response,
// and no other error happened
var ErrNoResponse = errors.New("no response to request")

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
19 20 21 22 23 24
// 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.
25
	HandleMessage(context.Context, msg.NetMessage) msg.NetMessage
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
26 27
}

28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
// Sender interface for network services.
type Sender interface {
	// SendMessage sends out a given message, without expecting a response.
	SendMessage(ctx context.Context, m msg.NetMessage) error

	// SendRequest sends out a given message, and awaits a response.
	// Set Deadlines or cancellations in the context.Context you pass in.
	SendRequest(ctx context.Context, m msg.NetMessage) (msg.NetMessage, error)
}

// Service is an interface for a net resource with both outgoing (sender) and
// incomig (SetHandler) requests.
type Service interface {
	Sender

	// Start + Stop Service
	Start(ctx context.Context) error
	Stop()

	// GetPipe
	GetPipe() *msg.Pipe

	// SetHandler assigns the request Handler for this service.
	SetHandler(Handler)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
52
	GetHandler() Handler
53 54
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
55 56
// Service is a networking component that protocols can use to multiplex
// messages over the same channel, and to issue + handle requests.
57
type service struct {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
	// 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
73 74
func NewService(h Handler) Service {
	return &service{
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
75 76 77 78 79 80 81
		Handler:  h,
		Requests: RequestMap{},
		Pipe:     msg.NewPipe(10),
	}
}

// Start kicks off the Service goroutines.
82
func (s *service) Start(ctx context.Context) error {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
83 84 85 86 87 88 89 90 91 92 93 94
	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.
95
func (s *service) Stop() {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
96 97 98 99
	s.cancel()
	s.cancel = context.CancelFunc(nil)
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
100
// GetPipe implements the mux.Protocol interface
101
func (s *service) GetPipe() *msg.Pipe {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
102 103 104
	return s.Pipe
}

105
// sendMessage sends a message out (actual leg work. SendMessage is to export w/o rid)
106
func (s *service) sendMessage(ctx context.Context, m msg.NetMessage, rid RequestID) error {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
107 108

	// serialize ServiceMessage wrapper
109
	data, err := wrapData(m.Data(), rid)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
110 111 112 113
	if err != nil {
		return err
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
114
	// log.Debug("Service send message [to = %s]", m.Peer())
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
115

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
116
	// send message
117
	m2 := msg.New(m.Peer(), data)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
118 119 120 121 122 123 124 125 126
	select {
	case s.Outgoing <- m2:
	case <-ctx.Done():
		return ctx.Err()
	}

	return nil
}

127
// SendMessage sends a message out
128
func (s *service) SendMessage(ctx context.Context, m msg.NetMessage) error {
129 130 131
	return s.sendMessage(ctx, m, nil)
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
132
// SendRequest sends a request message out and awaits a response.
133
func (s *service) SendRequest(ctx context.Context, m msg.NetMessage) (msg.NetMessage, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
134 135

	// create a request
136
	r, err := NewRequest(m.Peer().ID())
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
	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
161
	s.sendMessage(ctx, m, r.ID)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
162 163 164 165 166 167 168 169 170 171

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
172 173 174 175
	if m == nil {
		return nil, ErrNoResponse
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
176 177 178 179 180
	return m, err
}

// handleIncoming consumes the messages on the s.Incoming channel and
// routes them appropriately (to requests, or handler).
181
func (s *service) handleIncomingMessages(ctx context.Context) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
182 183
	for {
		select {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
184 185 186 187
		case m, more := <-s.Incoming:
			if !more {
				return
			}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
188 189 190 191 192 193 194 195
			go s.handleIncomingMessage(ctx, m)

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

196
func (s *service) handleIncomingMessage(ctx context.Context, m msg.NetMessage) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
197 198

	// unwrap the incoming message
199
	data, rid, err := unwrapData(m.Data())
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
200
	if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
201
		log.Error("de-serializing error: %v", err)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
202
	}
203
	m2 := msg.New(m.Peer(), data)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
204 205 206

	// if it's a request (or has no RequestID), handle it
	if rid == nil || rid.IsRequest() {
207
		if s.Handler == nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
208
			log.Error("service dropped msg: %v", m)
209 210 211
			return // no handler, drop it.
		}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
212
		// should this be "go HandleMessage ... ?"
213
		r1 := s.Handler.HandleMessage(ctx, m2)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
214 215 216

		// if handler gave us a response, send it back out!
		if r1 != nil {
217
			err := s.sendMessage(ctx, r1, rid.Response())
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
218
			if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
219
				log.Error("error sending response message: %v", err)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
220 221 222 223 224 225 226
			}
		}
		return
	}

	// Otherwise, it is a response. handle it.
	if !rid.IsResponse() {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
227
		log.Error("RequestID should identify a response here.")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
228 229
	}

230
	key := RequestKey(m.Peer().ID(), RequestID(rid))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
231 232 233 234 235
	s.RequestsLock.RLock()
	r, found := s.Requests[key]
	s.RequestsLock.RUnlock()

	if !found {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
236
		log.Error("no request key %v (timeout?)", []byte(key))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
237 238 239 240 241 242 243 244
		return
	}

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
246
// SetHandler assigns the request Handler for this service.
247
func (s *service) SetHandler(h Handler) {
248 249
	s.Handler = h
}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
250 251 252 253 254

// GetHandler returns the request Handler for this service.
func (s *service) GetHandler() Handler {
	return s.Handler
}