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

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

9 10
	"github.com/ipfs/go-graphsync/responsemanager/blockhooks"

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 17
	"github.com/ipfs/go-graphsync/responsemanager/requesthooks"
	"github.com/ipfs/go-graphsync/responsemanager/runtraversal"
	logging "github.com/ipfs/go-log"
18
	"github.com/ipfs/go-peertaskqueue/peertask"
19 20
	ipld "github.com/ipld/go-ipld-prime"
	cidlink "github.com/ipld/go-ipld-prime/linking/cid"
21
	"github.com/libp2p/go-libp2p-core/peer"
22 23
)

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

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

type inProgressResponseStatus struct {
32 33 34 35 36 37
	ctx       context.Context
	cancelFn  func()
	request   gsmsg.GraphSyncRequest
	loader    ipld.Loader
	traverser ipldutil.Traverser
	isPaused  bool
38 39 40 41
}

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

type responseTaskData struct {
46 47 48 49
	ctx       context.Context
	request   gsmsg.GraphSyncRequest
	loader    ipld.Loader
	traverser ipldutil.Traverser
50 51
}

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

62 63 64 65 66 67 68 69 70 71
// RequestHooks is an interface for processing request hooks
type RequestHooks interface {
	ProcessRequestHooks(p peer.ID, request graphsync.RequestData) requesthooks.Result
}

// BlockHooks is an interface for processing block hooks
type BlockHooks interface {
	ProcessBlockHooks(p peer.ID, request graphsync.RequestData, blockData graphsync.BlockData) blockhooks.Result
}

72 73 74 75 76 77 78 79 80 81 82 83
// 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 {
84 85 86 87 88 89 90 91 92 93 94 95
	ctx          context.Context
	cancelFn     context.CancelFunc
	loader       ipld.Loader
	peerManager  PeerManager
	queryQueue   QueryQueue
	requestHooks RequestHooks
	blockHooks   BlockHooks

	messages            chan responseManagerMessage
	workSignal          chan struct{}
	ticker              *time.Ticker
	inProgressResponses map[responseKey]*inProgressResponseStatus
96 97 98 99 100
}

// New creates a new response manager from the given context, loader,
// bridge to IPLD interface, peerManager, and queryQueue.
func New(ctx context.Context,
101
	loader ipld.Loader,
102
	peerManager PeerManager,
103 104 105
	queryQueue QueryQueue,
	requestHooks RequestHooks,
	blockHooks BlockHooks) *ResponseManager {
106 107 108 109 110 111 112
	ctx, cancelFn := context.WithCancel(ctx)
	return &ResponseManager{
		ctx:                 ctx,
		cancelFn:            cancelFn,
		loader:              loader,
		peerManager:         peerManager,
		queryQueue:          queryQueue,
113 114
		requestHooks:        requestHooks,
		blockHooks:          blockHooks,
115 116 117
		messages:            make(chan responseManagerMessage, 16),
		workSignal:          make(chan struct{}, 1),
		ticker:              time.NewTicker(thawSpeed),
118
		inProgressResponses: make(map[responseKey]*inProgressResponseStatus),
119 120 121 122 123 124 125 126 127
	}
}

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

// ProcessRequests processes incoming requests for the given peer
128
func (rm *ResponseManager) ProcessRequests(ctx context.Context, p peer.ID, requests []gsmsg.GraphSyncRequest) {
129 130 131
	select {
	case rm.messages <- &processRequestMessage{p, requests}:
	case <-rm.ctx.Done():
132
	case <-ctx.Done():
133 134 135
	}
}

136 137 138 139
type unpauseRequestMessage struct {
	p         peer.ID
	requestID graphsync.RequestID
	response  chan error
140 141
}

142 143 144 145 146 147 148 149 150 151 152 153 154
// 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
155 156 157
	}
}

158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
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
}

180
type finishTaskRequest struct {
181
	key responseKey
182 183 184 185 186 187 188
	err error
}

type setResponseDataRequest struct {
	key       responseKey
	loader    ipld.Loader
	traverser ipldutil.Traverser
189 190 191
}

func (rm *ResponseManager) processQueriesWorker() {
192
	const targetWork = 1
193 194 195
	taskDataChan := make(chan *responseTaskData)
	var taskData *responseTaskData
	for {
196 197
		pid, tasks, _ := rm.queryQueue.PopTasks(targetWork)
		for len(tasks) == 0 {
198 199 200 201
			select {
			case <-rm.ctx.Done():
				return
			case <-rm.workSignal:
202
				pid, tasks, _ = rm.queryQueue.PopTasks(targetWork)
203 204
			case <-rm.ticker.C:
				rm.queryQueue.ThawRound()
205
				pid, tasks, _ = rm.queryQueue.PopTasks(targetWork)
206 207
			}
		}
208 209
		for _, task := range tasks {
			key := task.Topic.(responseKey)
210 211 212 213 214 215 216 217 218 219
			select {
			case rm.messages <- &responseDataRequest{key, taskDataChan}:
			case <-rm.ctx.Done():
				return
			}
			select {
			case taskData = <-taskDataChan:
			case <-rm.ctx.Done():
				return
			}
220
			err := rm.executeTask(key, taskData)
221
			select {
222
			case rm.messages <- &finishTaskRequest{key, err}:
223 224 225
			case <-rm.ctx.Done():
			}
		}
226
		rm.queryQueue.TasksDone(pid, tasks...)
227

228 229 230 231
	}

}

232 233 234 235 236 237 238 239 240 241 242 243 244 245
func (rm *ResponseManager) executeTask(key responseKey, taskData *responseTaskData) error {
	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 {
			return err
		}
		select {
		case <-rm.ctx.Done():
			return nil
		case rm.messages <- &setResponseDataRequest{key, loader, traverser}:
		}
246
	}
247
	return rm.executeQuery(key.p, taskData.request, loader, traverser)
248 249
}

250
func (rm *ResponseManager) prepareQuery(ctx context.Context,
251
	p peer.ID,
252 253
	request gsmsg.GraphSyncRequest) (ipld.Loader, ipldutil.Traverser, error) {
	result := rm.requestHooks.ProcessRequestHooks(p, request)
254
	peerResponseSender := rm.peerManager.SenderForPeer(p)
255 256
	for _, extension := range result.Extensions {
		peerResponseSender.SendExtensionData(request.ID(), extension)
257
	}
258
	if result.Err != nil || !result.IsValidated {
259
		peerResponseSender.FinishWithError(request.ID(), graphsync.RequestFailedUnknown)
260
		return nil, nil, errors.New("request not valid")
261
	}
262
	rootLink := cidlink.Link{Cid: request.Root()}
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
	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
}

func (rm *ResponseManager) executeQuery(p peer.ID,
	request gsmsg.GraphSyncRequest,
	loader ipld.Loader,
	traverser ipldutil.Traverser) error {
	peerResponseSender := rm.peerManager.SenderForPeer(p)
	err := runtraversal.RunTraversal(loader, traverser, func(link ipld.Link, data []byte) error {
		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
	})
293
	if err != nil {
294 295 296 297
		if err != blockhooks.ErrPaused {
			peerResponseSender.FinishWithError(request.ID(), graphsync.RequestFailedUnknown)
		}
		return err
298 299
	}
	peerResponseSender.FinishRequest(request.ID())
300
	return nil
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 337 338 339 340
// 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] =
341
				&inProgressResponseStatus{
342 343
					ctx:      ctx,
					cancelFn: cancelFn,
344
					request:  request,
345
				}
346 347
			// TODO: Use a better work estimation metric.
			rm.queryQueue.PushTasks(prm.p, peertask.Task{Topic: key, Priority: int(request.Priority()), Work: 1})
348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365
			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 {
366
		taskData = &responseTaskData{response.ctx, response.request, response.loader, response.traverser}
367 368 369 370 371 372 373 374 375
	} else {
		taskData = nil
	}
	select {
	case <-rm.ctx.Done():
	case rdr.taskDataChan <- taskData:
	}
}

376 377
func (ftr *finishTaskRequest) handle(rm *ResponseManager) {
	response, ok := rm.inProgressResponses[ftr.key]
378 379 380
	if !ok {
		return
	}
381 382 383 384 385 386 387 388
	if ftr.err == blockhooks.ErrPaused {
		response.isPaused = true
		return
	}
	if ftr.err != nil {
		log.Infof("response failed: %w", ftr.err)
	}
	delete(rm.inProgressResponses, ftr.key)
389 390 391
	response.cancelFn()
}

392 393 394 395 396 397 398 399 400
func (srdr *setResponseDataRequest) handle(rm *ResponseManager) {
	response, ok := rm.inProgressResponses[srdr.key]
	if !ok {
		return
	}
	response.loader = srdr.loader
	response.traverser = srdr.traverser
}

401 402 403 404 405 406
func (sm *synchronizeMessage) handle(rm *ResponseManager) {
	select {
	case <-rm.ctx.Done():
	case sm.sync <- struct{}{}:
	}
}
407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432

func (urm *unpauseRequestMessage) unpauseRequest(rm *ResponseManager) error {
	key := responseKey{urm.p, urm.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(urm.p, peertask.Task{Topic: key, Priority: math.MaxInt32, Work: 1})
	select {
	case rm.workSignal <- struct{}{}:
	default:
	}
	return nil
}

func (urm *unpauseRequestMessage) handle(rm *ResponseManager) {
	err := urm.unpauseRequest(rm)
	select {
	case <-rm.ctx.Done():
	case urm.response <- err:
	}
}