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

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

Hannah Howard's avatar
Hannah Howard committed
9
	"github.com/ipfs/go-graphsync/responsemanager/hooks"
10

11
	"github.com/ipfs/go-graphsync"
12
	"github.com/ipfs/go-graphsync/ipldutil"
13 14
	gsmsg "github.com/ipfs/go-graphsync/message"
	"github.com/ipfs/go-graphsync/responsemanager/peerresponsemanager"
15 16
	"github.com/ipfs/go-graphsync/responsemanager/runtraversal"
	logging "github.com/ipfs/go-log"
17
	"github.com/ipfs/go-peertaskqueue/peertask"
18 19
	ipld "github.com/ipld/go-ipld-prime"
	cidlink "github.com/ipld/go-ipld-prime/linking/cid"
20
	"github.com/libp2p/go-libp2p-core/peer"
21 22
)

23 24
var log = logging.Logger("graphsync")

25 26 27 28 29 30
const (
	maxInProcessRequests = 6
	thawSpeed            = time.Millisecond * 100
)

type inProgressResponseStatus struct {
Hannah Howard's avatar
Hannah Howard committed
31 32 33 34 35 36 37 38
	ctx          context.Context
	cancelFn     func()
	request      gsmsg.GraphSyncRequest
	loader       ipld.Loader
	traverser    ipldutil.Traverser
	updateSignal chan struct{}
	updates      []gsmsg.GraphSyncRequest
	isPaused     bool
39 40 41 42
}

type responseKey struct {
	p         peer.ID
43
	requestID graphsync.RequestID
44 45 46
}

type responseTaskData struct {
Hannah Howard's avatar
Hannah Howard committed
47 48 49 50 51
	ctx          context.Context
	request      gsmsg.GraphSyncRequest
	loader       ipld.Loader
	traverser    ipldutil.Traverser
	updateSignal chan struct{}
52 53
}

54 55 56
// QueryQueue is an interface that can receive new selector query tasks
// and prioritize them as needed, and pop them off later
type QueryQueue interface {
57 58 59 60
	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)
61 62 63
	ThawRound()
}

64 65
// RequestHooks is an interface for processing request hooks
type RequestHooks interface {
Hannah Howard's avatar
Hannah Howard committed
66
	ProcessRequestHooks(p peer.ID, request graphsync.RequestData) hooks.RequestResult
67 68 69 70
}

// BlockHooks is an interface for processing block hooks
type BlockHooks interface {
Hannah Howard's avatar
Hannah Howard committed
71 72 73 74 75 76
	ProcessBlockHooks(p peer.ID, request graphsync.RequestData, blockData graphsync.BlockData) hooks.BlockResult
}

// UpdateHooks is an interface for processing update hooks
type UpdateHooks interface {
	ProcessUpdateHooks(p peer.ID, request graphsync.RequestData, update graphsync.RequestData) hooks.UpdateResult
77 78
}

79 80 81 82 83
// CompletedListeners is an interface for notifying listeners that responses are complete
type CompletedListeners interface {
	NotifyCompletedListeners(p peer.ID, request graphsync.RequestData, status graphsync.ResponseStatusCode)
}

84 85 86 87 88 89 90 91 92 93 94 95
// 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 {
Hannah Howard's avatar
Hannah Howard committed
96 97 98 99 100 101 102 103
	ctx                 context.Context
	cancelFn            context.CancelFunc
	loader              ipld.Loader
	peerManager         PeerManager
	queryQueue          QueryQueue
	requestHooks        RequestHooks
	blockHooks          BlockHooks
	updateHooks         UpdateHooks
104
	completedListeners  CompletedListeners
105 106 107 108
	messages            chan responseManagerMessage
	workSignal          chan struct{}
	ticker              *time.Ticker
	inProgressResponses map[responseKey]*inProgressResponseStatus
109 110 111 112 113
}

// New creates a new response manager from the given context, loader,
// bridge to IPLD interface, peerManager, and queryQueue.
func New(ctx context.Context,
114
	loader ipld.Loader,
115
	peerManager PeerManager,
116 117
	queryQueue QueryQueue,
	requestHooks RequestHooks,
Hannah Howard's avatar
Hannah Howard committed
118
	blockHooks BlockHooks,
119 120
	updateHooks UpdateHooks,
	completedListeners CompletedListeners) *ResponseManager {
121 122 123 124 125 126 127
	ctx, cancelFn := context.WithCancel(ctx)
	return &ResponseManager{
		ctx:                 ctx,
		cancelFn:            cancelFn,
		loader:              loader,
		peerManager:         peerManager,
		queryQueue:          queryQueue,
128 129
		requestHooks:        requestHooks,
		blockHooks:          blockHooks,
Hannah Howard's avatar
Hannah Howard committed
130
		updateHooks:         updateHooks,
131
		completedListeners:  completedListeners,
132 133 134
		messages:            make(chan responseManagerMessage, 16),
		workSignal:          make(chan struct{}, 1),
		ticker:              time.NewTicker(thawSpeed),
135
		inProgressResponses: make(map[responseKey]*inProgressResponseStatus),
136 137 138 139 140 141 142 143 144
	}
}

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

// ProcessRequests processes incoming requests for the given peer
145
func (rm *ResponseManager) ProcessRequests(ctx context.Context, p peer.ID, requests []gsmsg.GraphSyncRequest) {
146 147 148
	select {
	case rm.messages <- &processRequestMessage{p, requests}:
	case <-rm.ctx.Done():
149
	case <-ctx.Done():
150 151 152
	}
}

153 154 155 156
type unpauseRequestMessage struct {
	p         peer.ID
	requestID graphsync.RequestID
	response  chan error
157 158
}

159 160 161 162 163 164 165 166 167 168 169 170 171
// UnpauseResponse unpauses a response that was previously paused
func (rm *ResponseManager) UnpauseResponse(p peer.ID, requestID graphsync.RequestID) error {
	response := make(chan error, 1)
	select {
	case <-rm.ctx.Done():
		return errors.New("Context Cancelled")
	case rm.messages <- &unpauseRequestMessage{p, requestID, response}:
	}
	select {
	case <-rm.ctx.Done():
		return errors.New("Context Cancelled")
	case err := <-response:
		return err
172 173 174
	}
}

175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
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
}

197
type finishTaskRequest struct {
198 199 200
	key    responseKey
	status graphsync.ResponseStatusCode
	err    error
201 202 203 204 205 206
}

type setResponseDataRequest struct {
	key       responseKey
	loader    ipld.Loader
	traverser ipldutil.Traverser
207 208
}

Hannah Howard's avatar
Hannah Howard committed
209 210 211 212 213
type responseUpdateRequest struct {
	key        responseKey
	updateChan chan []gsmsg.GraphSyncRequest
}

214
func (rm *ResponseManager) processQueriesWorker() {
215
	const targetWork = 1
216 217 218
	taskDataChan := make(chan *responseTaskData)
	var taskData *responseTaskData
	for {
219 220
		pid, tasks, _ := rm.queryQueue.PopTasks(targetWork)
		for len(tasks) == 0 {
221 222 223 224
			select {
			case <-rm.ctx.Done():
				return
			case <-rm.workSignal:
225
				pid, tasks, _ = rm.queryQueue.PopTasks(targetWork)
226 227
			case <-rm.ticker.C:
				rm.queryQueue.ThawRound()
228
				pid, tasks, _ = rm.queryQueue.PopTasks(targetWork)
229 230
			}
		}
231 232
		for _, task := range tasks {
			key := task.Topic.(responseKey)
233 234 235 236 237 238 239 240 241 242
			select {
			case rm.messages <- &responseDataRequest{key, taskDataChan}:
			case <-rm.ctx.Done():
				return
			}
			select {
			case taskData = <-taskDataChan:
			case <-rm.ctx.Done():
				return
			}
243
			status, err := rm.executeTask(key, taskData)
244
			select {
245
			case rm.messages <- &finishTaskRequest{key, status, err}:
246 247 248
			case <-rm.ctx.Done():
			}
		}
249
		rm.queryQueue.TasksDone(pid, tasks...)
250

251 252 253 254
	}

}

255
func (rm *ResponseManager) executeTask(key responseKey, taskData *responseTaskData) (graphsync.ResponseStatusCode, error) {
256 257 258 259 260 261
	var err error
	loader := taskData.loader
	traverser := taskData.traverser
	if loader == nil || traverser == nil {
		loader, traverser, err = rm.prepareQuery(taskData.ctx, key.p, taskData.request)
		if err != nil {
262
			return graphsync.RequestFailedUnknown, err
263 264 265
		}
		select {
		case <-rm.ctx.Done():
266
			return graphsync.RequestFailedUnknown, errors.New("context cancelled")
267 268
		case rm.messages <- &setResponseDataRequest{key, loader, traverser}:
		}
269
	}
Hannah Howard's avatar
Hannah Howard committed
270
	return rm.executeQuery(key.p, taskData.request, loader, traverser, taskData.updateSignal)
271 272
}

273
func (rm *ResponseManager) prepareQuery(ctx context.Context,
274
	p peer.ID,
275 276
	request gsmsg.GraphSyncRequest) (ipld.Loader, ipldutil.Traverser, error) {
	result := rm.requestHooks.ProcessRequestHooks(p, request)
277
	peerResponseSender := rm.peerManager.SenderForPeer(p)
278 279
	for _, extension := range result.Extensions {
		peerResponseSender.SendExtensionData(request.ID(), extension)
280
	}
281
	if result.Err != nil || !result.IsValidated {
282
		peerResponseSender.FinishWithError(request.ID(), graphsync.RequestFailedUnknown)
283
		return nil, nil, errors.New("request not valid")
284
	}
285
	rootLink := cidlink.Link{Cid: request.Root()}
286 287 288 289 290 291 292 293 294 295 296 297
	traverser := ipldutil.TraversalBuilder{
		Root:     rootLink,
		Selector: request.Selector(),
		Chooser:  result.CustomChooser,
	}.Start(ctx)
	loader := result.CustomLoader
	if loader == nil {
		loader = rm.loader
	}
	return loader, traverser, nil
}

Hannah Howard's avatar
Hannah Howard committed
298 299
func (rm *ResponseManager) executeQuery(
	p peer.ID,
300 301
	request gsmsg.GraphSyncRequest,
	loader ipld.Loader,
Hannah Howard's avatar
Hannah Howard committed
302
	traverser ipldutil.Traverser,
303
	updateSignal chan struct{}) (graphsync.ResponseStatusCode, error) {
Hannah Howard's avatar
Hannah Howard committed
304
	updateChan := make(chan []gsmsg.GraphSyncRequest)
305 306
	peerResponseSender := rm.peerManager.SenderForPeer(p)
	err := runtraversal.RunTraversal(loader, traverser, func(link ipld.Link, data []byte) error {
Hannah Howard's avatar
Hannah Howard committed
307 308 309 310
		err := rm.checkForUpdates(p, request, updateSignal, updateChan, peerResponseSender)
		if err != nil {
			return err
		}
311 312 313 314 315 316 317 318 319 320 321 322
		blockData := peerResponseSender.SendResponse(request.ID(), link, data)
		if blockData.BlockSize() > 0 {
			result := rm.blockHooks.ProcessBlockHooks(p, request, blockData)
			for _, extension := range result.Extensions {
				peerResponseSender.SendExtensionData(request.ID(), extension)
			}
			if result.Err != nil {
				return result.Err
			}
		}
		return nil
	})
323
	if err != nil {
Hannah Howard's avatar
Hannah Howard committed
324
		if err != hooks.ErrPaused {
325
			peerResponseSender.FinishWithError(request.ID(), graphsync.RequestFailedUnknown)
326
			return graphsync.RequestFailedUnknown, err
327
		}
328 329
		peerResponseSender.PauseRequest(request.ID())
		return graphsync.RequestPaused, err
330
	}
331
	return peerResponseSender.FinishRequest(request.ID()), nil
332 333
}

Hannah Howard's avatar
Hannah Howard committed
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363
func (rm *ResponseManager) checkForUpdates(
	p peer.ID,
	request gsmsg.GraphSyncRequest,
	updateSignal chan struct{},
	updateChan chan []gsmsg.GraphSyncRequest,
	peerResponseSender peerresponsemanager.PeerResponseSender) error {
	select {
	case <-updateSignal:
		select {
		case rm.messages <- &responseUpdateRequest{responseKey{p, request.ID()}, updateChan}:
		case <-rm.ctx.Done():
		}
		select {
		case updates := <-updateChan:
			for _, update := range updates {
				result := rm.updateHooks.ProcessUpdateHooks(p, request, update)
				for _, extension := range result.Extensions {
					peerResponseSender.SendExtensionData(request.ID(), extension)
				}
				if result.Err != nil {
					return result.Err
				}
			}
		case <-rm.ctx.Done():
		}
	default:
	}
	return nil
}

364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398
// 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()}
Hannah Howard's avatar
Hannah Howard committed
399
		if request.IsCancel() {
400 401 402 403
			rm.queryQueue.Remove(key, key.p)
			response, ok := rm.inProgressResponses[key]
			if ok {
				response.cancelFn()
Hannah Howard's avatar
Hannah Howard committed
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418
				delete(rm.inProgressResponses, key)
			}
			continue
		}
		if request.IsUpdate() {
			rm.processUpdate(key, request)
			continue
		}
		ctx, cancelFn := context.WithCancel(rm.ctx)
		rm.inProgressResponses[key] =
			&inProgressResponseStatus{
				ctx:          ctx,
				cancelFn:     cancelFn,
				request:      request,
				updateSignal: make(chan struct{}, 1),
419
			}
Hannah Howard's avatar
Hannah Howard committed
420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457
		// TODO: Use a better work estimation metric.
		rm.queryQueue.PushTasks(prm.p, peertask.Task{Topic: key, Priority: int(request.Priority()), Work: 1})
		select {
		case rm.workSignal <- struct{}{}:
		default:
		}
	}
}

func (rm *ResponseManager) processUpdate(key responseKey, update gsmsg.GraphSyncRequest) {
	response, ok := rm.inProgressResponses[key]
	if !ok {
		log.Warnf("received update for non existent request, peer %s, request ID %d", key.p.Pretty(), key.requestID)
		return
	}
	if !response.isPaused {
		response.updates = append(response.updates, update)
		select {
		case response.updateSignal <- struct{}{}:
		default:
		}
		return
	}
	result := rm.updateHooks.ProcessUpdateHooks(key.p, response.request, update)
	peerResponseSender := rm.peerManager.SenderForPeer(key.p)
	for _, extension := range result.Extensions {
		peerResponseSender.SendExtensionData(key.requestID, extension)
	}
	if result.Err != nil {
		peerResponseSender.FinishWithError(key.requestID, graphsync.RequestFailedUnknown)
		delete(rm.inProgressResponses, key)
		response.cancelFn()
		return
	}
	if result.Unpause {
		err := rm.unpauseRequest(key.p, key.requestID)
		if err != nil {
			log.Warnf("error unpausing request: %s", err.Error())
458 459 460 461
		}
	}
}

Hannah Howard's avatar
Hannah Howard committed
462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479
func (rm *ResponseManager) unpauseRequest(p peer.ID, requestID graphsync.RequestID) error {
	key := responseKey{p, requestID}
	inProgressResponse, ok := rm.inProgressResponses[key]
	if !ok {
		return errors.New("could not find request")
	}
	if !inProgressResponse.isPaused {
		return errors.New("request is not paused")
	}
	inProgressResponse.isPaused = false
	rm.queryQueue.PushTasks(p, peertask.Task{Topic: key, Priority: math.MaxInt32, Work: 1})
	select {
	case rm.workSignal <- struct{}{}:
	default:
	}
	return nil
}

480 481 482 483
func (rdr *responseDataRequest) handle(rm *ResponseManager) {
	response, ok := rm.inProgressResponses[rdr.key]
	var taskData *responseTaskData
	if ok {
Hannah Howard's avatar
Hannah Howard committed
484
		taskData = &responseTaskData{response.ctx, response.request, response.loader, response.traverser, response.updateSignal}
485 486 487 488 489 490 491 492 493
	} else {
		taskData = nil
	}
	select {
	case <-rm.ctx.Done():
	case rdr.taskDataChan <- taskData:
	}
}

494 495
func (ftr *finishTaskRequest) handle(rm *ResponseManager) {
	response, ok := rm.inProgressResponses[ftr.key]
496 497 498
	if !ok {
		return
	}
Hannah Howard's avatar
Hannah Howard committed
499
	if ftr.err == hooks.ErrPaused {
500 501 502
		response.isPaused = true
		return
	}
503
	rm.completedListeners.NotifyCompletedListeners(ftr.key.p, response.request, ftr.status)
504 505 506 507
	if ftr.err != nil {
		log.Infof("response failed: %w", ftr.err)
	}
	delete(rm.inProgressResponses, ftr.key)
508 509 510
	response.cancelFn()
}

511 512 513 514 515 516 517 518 519
func (srdr *setResponseDataRequest) handle(rm *ResponseManager) {
	response, ok := rm.inProgressResponses[srdr.key]
	if !ok {
		return
	}
	response.loader = srdr.loader
	response.traverser = srdr.traverser
}

Hannah Howard's avatar
Hannah Howard committed
520 521 522 523 524 525 526 527 528
func (rur *responseUpdateRequest) handle(rm *ResponseManager) {
	response, ok := rm.inProgressResponses[rur.key]
	var updates []gsmsg.GraphSyncRequest
	if ok {
		updates = response.updates
		response.updates = nil
	} else {
		updates = nil
	}
529 530
	select {
	case <-rm.ctx.Done():
Hannah Howard's avatar
Hannah Howard committed
531
	case rur.updateChan <- updates:
532 533
	}
}
534

Hannah Howard's avatar
Hannah Howard committed
535
func (sm *synchronizeMessage) handle(rm *ResponseManager) {
536
	select {
Hannah Howard's avatar
Hannah Howard committed
537 538
	case <-rm.ctx.Done():
	case sm.sync <- struct{}{}:
539 540 541 542
	}
}

func (urm *unpauseRequestMessage) handle(rm *ResponseManager) {
Hannah Howard's avatar
Hannah Howard committed
543
	err := rm.unpauseRequest(urm.p, urm.requestID)
544 545 546 547 548
	select {
	case <-rm.ctx.Done():
	case urm.response <- err:
	}
}