responsemanager.go 10 KB
Newer Older
1 2 3 4
package responsemanager

import (
	"context"
5
	"errors"
6
	"sync"
7 8
	"time"

9
	"github.com/ipfs/go-graphsync"
10
	"github.com/ipfs/go-graphsync/ipldutil"
11
	gsmsg "github.com/ipfs/go-graphsync/message"
12
	"github.com/ipfs/go-graphsync/responsemanager/loader"
13
	"github.com/ipfs/go-graphsync/responsemanager/peerresponsemanager"
14
	"github.com/ipfs/go-peertaskqueue/peertask"
15 16
	ipld "github.com/ipld/go-ipld-prime"
	cidlink "github.com/ipld/go-ipld-prime/linking/cid"
17
	"github.com/ipld/go-ipld-prime/traversal"
18
	"github.com/libp2p/go-libp2p-core/peer"
19 20 21 22 23 24 25 26 27 28
)

const (
	maxInProcessRequests = 6
	thawSpeed            = time.Millisecond * 100
)

type inProgressResponseStatus struct {
	ctx      context.Context
	cancelFn func()
29
	request  gsmsg.GraphSyncRequest
30 31 32 33
}

type responseKey struct {
	p         peer.ID
34
	requestID graphsync.RequestID
35 36 37
}

type responseTaskData struct {
38 39
	ctx     context.Context
	request gsmsg.GraphSyncRequest
40 41
}

42
type requestHook struct {
43
	key  uint64
44
	hook graphsync.OnIncomingRequestHook
45 46
}

47 48 49
// QueryQueue is an interface that can receive new selector query tasks
// and prioritize them as needed, and pop them off later
type QueryQueue interface {
50 51 52 53
	PushTasks(to peer.ID, tasks ...peertask.Task)
	PopTasks(targetMinWork int) (peer.ID, []*peertask.Task, int)
	Remove(topic peertask.Topic, p peer.ID)
	TasksDone(to peer.ID, tasks ...*peertask.Task)
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
	ThawRound()
}

// PeerManager is an interface that returns sender interfaces for peer responses.
type PeerManager interface {
	SenderForPeer(p peer.ID) peerresponsemanager.PeerResponseSender
}

type responseManagerMessage interface {
	handle(rm *ResponseManager)
}

// ResponseManager handles incoming requests from the network, initiates selector
// traversals, and transmits responses
type ResponseManager struct {
	ctx         context.Context
	cancelFn    context.CancelFunc
71
	loader      ipld.Loader
72 73 74
	peerManager PeerManager
	queryQueue  QueryQueue

75 76 77 78 79 80 81 82 83
	messages             chan responseManagerMessage
	workSignal           chan struct{}
	ticker               *time.Ticker
	inProgressResponses  map[responseKey]inProgressResponseStatus
	requestHooksLk       sync.RWMutex
	requestHookNextKey   uint64
	requestHooks         []requestHook
	persistenceOptionsLk sync.RWMutex
	persistenceOptions   map[string]ipld.Loader
84 85 86 87 88
}

// New creates a new response manager from the given context, loader,
// bridge to IPLD interface, peerManager, and queryQueue.
func New(ctx context.Context,
89
	loader ipld.Loader,
90 91 92 93 94 95 96 97 98 99 100 101 102
	peerManager PeerManager,
	queryQueue QueryQueue) *ResponseManager {
	ctx, cancelFn := context.WithCancel(ctx)
	return &ResponseManager{
		ctx:                 ctx,
		cancelFn:            cancelFn,
		loader:              loader,
		peerManager:         peerManager,
		queryQueue:          queryQueue,
		messages:            make(chan responseManagerMessage, 16),
		workSignal:          make(chan struct{}, 1),
		ticker:              time.NewTicker(thawSpeed),
		inProgressResponses: make(map[responseKey]inProgressResponseStatus),
103
		persistenceOptions:  make(map[string]ipld.Loader),
104 105 106 107 108 109 110 111 112
	}
}

type processRequestMessage struct {
	p        peer.ID
	requests []gsmsg.GraphSyncRequest
}

// ProcessRequests processes incoming requests for the given peer
113
func (rm *ResponseManager) ProcessRequests(ctx context.Context, p peer.ID, requests []gsmsg.GraphSyncRequest) {
114 115 116
	select {
	case rm.messages <- &processRequestMessage{p, requests}:
	case <-rm.ctx.Done():
117
	case <-ctx.Done():
118 119 120
	}
}

121 122 123 124 125 126 127 128 129 130 131 132 133 134
// RegisterPersistenceOption registers a new loader for the response manager
func (rm *ResponseManager) RegisterPersistenceOption(name string, loader ipld.Loader) error {
	rm.persistenceOptionsLk.Lock()
	defer rm.persistenceOptionsLk.Unlock()
	_, ok := rm.persistenceOptions[name]
	if ok {
		return errors.New("persistence option alreayd registered")
	}
	rm.persistenceOptions[name] = loader
	return nil
}

// RegisterRequestHook registers an extension to process new incoming requests
func (rm *ResponseManager) RegisterRequestHook(hook graphsync.OnIncomingRequestHook) graphsync.UnregisterHookFunc {
135 136 137 138 139 140 141 142 143 144 145 146 147 148
	rm.requestHooksLk.Lock()
	rh := requestHook{rm.requestHookNextKey, hook}
	rm.requestHookNextKey++
	rm.requestHooks = append(rm.requestHooks, rh)
	rm.requestHooksLk.Unlock()
	return func() {
		rm.requestHooksLk.Lock()
		defer rm.requestHooksLk.Unlock()
		for i, matchHook := range rm.requestHooks {
			if rh.key == matchHook.key {
				rm.requestHooks = append(rm.requestHooks[:i], rm.requestHooks[i+1:]...)
				return
			}
		}
149 150 151
	}
}

152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
type synchronizeMessage struct {
	sync chan struct{}
}

// this is a test utility method to force all messages to get processed
func (rm *ResponseManager) synchronize() {
	sync := make(chan struct{})
	select {
	case rm.messages <- &synchronizeMessage{sync}:
	case <-rm.ctx.Done():
	}
	select {
	case <-sync:
	case <-rm.ctx.Done():
	}
}

type responseDataRequest struct {
	key          responseKey
	taskDataChan chan *responseTaskData
}

type finishResponseRequest struct {
	key responseKey
}

func (rm *ResponseManager) processQueriesWorker() {
179
	const targetWork = 1
180 181 182
	taskDataChan := make(chan *responseTaskData)
	var taskData *responseTaskData
	for {
183 184
		pid, tasks, _ := rm.queryQueue.PopTasks(targetWork)
		for len(tasks) == 0 {
185 186 187 188
			select {
			case <-rm.ctx.Done():
				return
			case <-rm.workSignal:
189
				pid, tasks, _ = rm.queryQueue.PopTasks(targetWork)
190 191
			case <-rm.ticker.C:
				rm.queryQueue.ThawRound()
192
				pid, tasks, _ = rm.queryQueue.PopTasks(targetWork)
193 194
			}
		}
195 196
		for _, task := range tasks {
			key := task.Topic.(responseKey)
197 198 199 200 201 202 203 204 205 206
			select {
			case rm.messages <- &responseDataRequest{key, taskDataChan}:
			case <-rm.ctx.Done():
				return
			}
			select {
			case taskData = <-taskDataChan:
			case <-rm.ctx.Done():
				return
			}
207
			rm.executeQuery(taskData.ctx, key.p, taskData.request)
208 209 210 211 212
			select {
			case rm.messages <- &finishResponseRequest{key}:
			case <-rm.ctx.Done():
			}
		}
213
		rm.queryQueue.TasksDone(pid, tasks...)
214

215 216 217 218
	}

}

219
func noopVisitor(tp traversal.Progress, n ipld.Node, tr traversal.VisitReason) error {
220 221 222
	return nil
}

223
type hookActions struct {
224
	persistenceOptions map[string]ipld.Loader
225 226 227 228
	isValidated        bool
	requestID          graphsync.RequestID
	peerResponseSender peerresponsemanager.PeerResponseSender
	err                error
229 230
	loader             ipld.Loader
	chooser            traversal.NodeBuilderChooser
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
}

func (ha *hookActions) SendExtensionData(ext graphsync.ExtensionData) {
	ha.peerResponseSender.SendExtensionData(ha.requestID, ext)
}

func (ha *hookActions) TerminateWithError(err error) {
	ha.err = err
	ha.peerResponseSender.FinishWithError(ha.requestID, graphsync.RequestFailedUnknown)
}

func (ha *hookActions) ValidateRequest() {
	ha.isValidated = true
}

246 247 248 249 250 251
func (ha *hookActions) UsePersistenceOption(name string) {
	loader, ok := ha.persistenceOptions[name]
	if !ok {
		ha.TerminateWithError(errors.New("unknown loader option"))
		return
	}
252 253 254 255 256 257 258
	ha.loader = loader
}

func (ha *hookActions) UseNodeBuilderChooser(chooser traversal.NodeBuilderChooser) {
	ha.chooser = chooser
}

259 260
func (rm *ResponseManager) executeQuery(ctx context.Context,
	p peer.ID,
261
	request gsmsg.GraphSyncRequest) {
262
	peerResponseSender := rm.peerManager.SenderForPeer(p)
263
	selectorSpec := request.Selector()
264
	rm.requestHooksLk.RLock()
265 266
	rm.persistenceOptionsLk.RLock()
	ha := &hookActions{rm.persistenceOptions, false, request.ID(), peerResponseSender, nil, rm.loader, nil}
267 268 269
	for _, requestHook := range rm.requestHooks {
		requestHook.hook(p, request, ha)
		if ha.err != nil {
270
			rm.requestHooksLk.RUnlock()
271
			rm.persistenceOptionsLk.RUnlock()
272 273 274
			return
		}
	}
275
	rm.persistenceOptionsLk.RUnlock()
276
	rm.requestHooksLk.RUnlock()
277
	if !ha.isValidated {
278 279
		peerResponseSender.FinishWithError(request.ID(), graphsync.RequestFailedUnknown)
		return
280
	}
281
	selector, err := ipldutil.ParseSelector(selectorSpec)
282 283 284 285
	if err != nil {
		peerResponseSender.FinishWithError(request.ID(), graphsync.RequestFailedUnknown)
		return
	}
286
	rootLink := cidlink.Link{Cid: request.Root()}
287 288
	wrappedLoader := loader.WrapLoader(ctx, ha.loader, request.ID(), peerResponseSender)
	err = ipldutil.Traverse(ctx, wrappedLoader, ha.chooser, rootLink, selector, noopVisitor)
289 290 291 292 293 294 295
	if err != nil {
		peerResponseSender.FinishWithError(request.ID(), graphsync.RequestFailedUnknown)
		return
	}
	peerResponseSender.FinishRequest(request.ID())
}

296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336
// Startup starts processing for the WantManager.
func (rm *ResponseManager) Startup() {
	go rm.run()
}

// Shutdown ends processing for the want manager.
func (rm *ResponseManager) Shutdown() {
	rm.cancelFn()
}

func (rm *ResponseManager) cleanupInProcessResponses() {
	for _, response := range rm.inProgressResponses {
		response.cancelFn()
	}
}

func (rm *ResponseManager) run() {
	defer rm.cleanupInProcessResponses()
	for i := 0; i < maxInProcessRequests; i++ {
		go rm.processQueriesWorker()
	}

	for {
		select {
		case <-rm.ctx.Done():
			return
		case message := <-rm.messages:
			message.handle(rm)
		}
	}
}

func (prm *processRequestMessage) handle(rm *ResponseManager) {
	for _, request := range prm.requests {
		key := responseKey{p: prm.p, requestID: request.ID()}
		if !request.IsCancel() {
			ctx, cancelFn := context.WithCancel(rm.ctx)
			rm.inProgressResponses[key] =
				inProgressResponseStatus{
					ctx:      ctx,
					cancelFn: cancelFn,
337
					request:  request,
338
				}
339 340
			// TODO: Use a better work estimation metric.
			rm.queryQueue.PushTasks(prm.p, peertask.Task{Topic: key, Priority: int(request.Priority()), Work: 1})
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358
			select {
			case rm.workSignal <- struct{}{}:
			default:
			}
		} else {
			rm.queryQueue.Remove(key, key.p)
			response, ok := rm.inProgressResponses[key]
			if ok {
				response.cancelFn()
			}
		}
	}
}

func (rdr *responseDataRequest) handle(rm *ResponseManager) {
	response, ok := rm.inProgressResponses[rdr.key]
	var taskData *responseTaskData
	if ok {
359
		taskData = &responseTaskData{response.ctx, response.request}
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
	} else {
		taskData = nil
	}
	select {
	case <-rm.ctx.Done():
	case rdr.taskDataChan <- taskData:
	}
}

func (frr *finishResponseRequest) handle(rm *ResponseManager) {
	response, ok := rm.inProgressResponses[frr.key]
	if !ok {
		return
	}
	delete(rm.inProgressResponses, frr.key)
	response.cancelFn()
}

func (sm *synchronizeMessage) handle(rm *ResponseManager) {
	select {
	case <-rm.ctx.Done():
	case sm.sync <- struct{}{}:
	}
}