requestmanager.go 19.4 KB
Newer Older
1 2 3 4
package requestmanager

import (
	"context"
5
	"errors"
6
	"fmt"
Hannah Howard's avatar
Hannah Howard committed
7
	"sync/atomic"
8

Hannah Howard's avatar
Hannah Howard committed
9
	blocks "github.com/ipfs/go-block-format"
10
	"github.com/ipfs/go-cid"
Hannah Howard's avatar
Hannah Howard committed
11 12 13 14
	logging "github.com/ipfs/go-log"
	"github.com/ipld/go-ipld-prime"
	cidlink "github.com/ipld/go-ipld-prime/linking/cid"
	"github.com/libp2p/go-libp2p-core/peer"
Hannah Howard's avatar
Hannah Howard committed
15

16
	"github.com/ipfs/go-graphsync"
Hannah Howard's avatar
Hannah Howard committed
17
	"github.com/ipfs/go-graphsync/cidset"
Hannah Howard's avatar
Hannah Howard committed
18
	"github.com/ipfs/go-graphsync/dedupkey"
19
	ipldutil "github.com/ipfs/go-graphsync/ipldutil"
20
	"github.com/ipfs/go-graphsync/listeners"
21
	gsmsg "github.com/ipfs/go-graphsync/message"
22
	"github.com/ipfs/go-graphsync/messagequeue"
23
	"github.com/ipfs/go-graphsync/metadata"
24
	"github.com/ipfs/go-graphsync/notifications"
Hannah Howard's avatar
Hannah Howard committed
25 26
	"github.com/ipfs/go-graphsync/requestmanager/executor"
	"github.com/ipfs/go-graphsync/requestmanager/hooks"
27
	"github.com/ipfs/go-graphsync/requestmanager/types"
28 29
)

30
var log = logging.Logger("graphsync")
31 32

const (
33 34
	// defaultPriority is the default priority for requests sent by graphsync
	defaultPriority = graphsync.Priority(0)
35 36 37
)

type inProgressRequestStatus struct {
38 39 40 41 42 43 44 45
	ctx            context.Context
	cancelFn       func()
	p              peer.ID
	networkError   chan error
	resumeMessages chan []graphsync.ExtensionData
	pauseMessages  chan struct{}
	paused         bool
	lastResponse   atomic.Value
46 47 48 49
}

// PeerHandler is an interface that can send requests to peers
type PeerHandler interface {
50
	BuildMessage(p peer.ID, blkSize uint64, buildMessageFn func(*gsmsg.Builder), notifees []notifications.Notifee)
51 52
}

53 54 55
// AsyncLoader is an interface for loading links asynchronously, returning
// results as new responses are processed
type AsyncLoader interface {
56
	StartRequest(graphsync.RequestID, string) error
57
	ProcessResponse(responses map[graphsync.RequestID]metadata.Metadata,
58
		blks []blocks.Block)
59 60 61
	AsyncLoad(requestID graphsync.RequestID, link ipld.Link) <-chan types.AsyncLoadResult
	CompleteResponsesFor(requestID graphsync.RequestID)
	CleanupRequest(requestID graphsync.RequestID)
62 63
}

64 65 66 67 68 69 70 71
// RequestManager tracks outgoing requests and processes incoming reponses
// to them.
type RequestManager struct {
	ctx         context.Context
	cancel      func()
	messages    chan requestManagerMessage
	peerHandler PeerHandler
	rc          *responseCollector
72
	asyncLoader AsyncLoader
73
	// dont touch out side of run loop
74 75
	nextRequestID             graphsync.RequestID
	inProgressRequestStatuses map[graphsync.RequestID]*inProgressRequestStatus
Hannah Howard's avatar
Hannah Howard committed
76 77 78
	requestHooks              RequestHooks
	responseHooks             ResponseHooks
	blockHooks                BlockHooks
79
	networkErrorListeners     *listeners.NetworkErrorListeners
80 81 82 83 84 85
}

type requestManagerMessage interface {
	handle(rm *RequestManager)
}

Hannah Howard's avatar
Hannah Howard committed
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
// RequestHooks run for new requests
type RequestHooks interface {
	ProcessRequestHooks(p peer.ID, request graphsync.RequestData) hooks.RequestResult
}

// ResponseHooks run for new responses
type ResponseHooks interface {
	ProcessResponseHooks(p peer.ID, response graphsync.ResponseData) hooks.UpdateResult
}

// BlockHooks run for each block loaded
type BlockHooks interface {
	ProcessBlockHooks(p peer.ID, response graphsync.ResponseData, block graphsync.BlockData) hooks.UpdateResult
}

101
// New generates a new request manager from a context, network, and selectorQuerier
Hannah Howard's avatar
Hannah Howard committed
102 103
func New(ctx context.Context,
	asyncLoader AsyncLoader,
Hannah Howard's avatar
Hannah Howard committed
104 105
	requestHooks RequestHooks,
	responseHooks ResponseHooks,
106 107 108
	blockHooks BlockHooks,
	networkErrorListeners *listeners.NetworkErrorListeners,
) *RequestManager {
109 110 111 112
	ctx, cancel := context.WithCancel(ctx)
	return &RequestManager{
		ctx:                       ctx,
		cancel:                    cancel,
113
		asyncLoader:               asyncLoader,
114 115
		rc:                        newResponseCollector(ctx),
		messages:                  make(chan requestManagerMessage, 16),
116
		inProgressRequestStatuses: make(map[graphsync.RequestID]*inProgressRequestStatus),
Hannah Howard's avatar
Hannah Howard committed
117 118
		requestHooks:              requestHooks,
		responseHooks:             responseHooks,
Hannah Howard's avatar
Hannah Howard committed
119
		blockHooks:                blockHooks,
120
		networkErrorListeners:     networkErrorListeners,
121 122 123 124 125 126 127 128 129
	}
}

// SetDelegate specifies who will send messages out to the internet.
func (rm *RequestManager) SetDelegate(peerHandler PeerHandler) {
	rm.peerHandler = peerHandler
}

type inProgressRequest struct {
130 131
	requestID     graphsync.RequestID
	incoming      chan graphsync.ResponseProgress
132
	incomingError chan error
133 134 135 136
}

type newRequestMessage struct {
	p                     peer.ID
137
	root                  ipld.Link
138
	selector              ipld.Node
139
	extensions            []graphsync.ExtensionData
140 141 142 143
	inProgressRequestChan chan<- inProgressRequest
}

// SendRequest initiates a new GraphSync request to the given peer.
144 145
func (rm *RequestManager) SendRequest(ctx context.Context,
	p peer.ID,
146
	root ipld.Link,
147 148
	selector ipld.Node,
	extensions ...graphsync.ExtensionData) (<-chan graphsync.ResponseProgress, <-chan error) {
149
	if _, err := ipldutil.ParseSelector(selector); err != nil {
150
		return rm.singleErrorResponse(fmt.Errorf("Invalid Selector Spec"))
151 152 153 154 155
	}

	inProgressRequestChan := make(chan inProgressRequest)

	select {
156
	case rm.messages <- &newRequestMessage{p, root, selector, extensions, inProgressRequestChan}:
157
	case <-rm.ctx.Done():
158
		return rm.emptyResponse()
159
	case <-ctx.Done():
160
		return rm.emptyResponse()
161 162 163 164
	}
	var receivedInProgressRequest inProgressRequest
	select {
	case <-rm.ctx.Done():
165
		return rm.emptyResponse()
166 167 168
	case receivedInProgressRequest = <-inProgressRequestChan:
	}

169 170 171 172 173 174 175 176 177 178
	return rm.rc.collectResponses(ctx,
		receivedInProgressRequest.incoming,
		receivedInProgressRequest.incomingError,
		func() {
			rm.cancelRequest(receivedInProgressRequest.requestID,
				receivedInProgressRequest.incoming,
				receivedInProgressRequest.incomingError)
		})
}

179 180
func (rm *RequestManager) emptyResponse() (chan graphsync.ResponseProgress, chan error) {
	ch := make(chan graphsync.ResponseProgress)
181
	close(ch)
182
	errCh := make(chan error)
183 184 185 186
	close(errCh)
	return ch, errCh
}

187 188
func (rm *RequestManager) singleErrorResponse(err error) (chan graphsync.ResponseProgress, chan error) {
	ch := make(chan graphsync.ResponseProgress)
189
	close(ch)
190
	errCh := make(chan error, 1)
191
	errCh <- err
192 193
	close(errCh)
	return ch, errCh
194 195 196
}

type cancelRequestMessage struct {
197
	requestID graphsync.RequestID
198
	isPause   bool
199 200
}

201 202
func (rm *RequestManager) cancelRequest(requestID graphsync.RequestID,
	incomingResponses chan graphsync.ResponseProgress,
203
	incomingErrors chan error) {
204
	cancelMessageChannel := rm.messages
205
	for cancelMessageChannel != nil || incomingResponses != nil || incomingErrors != nil {
206
		select {
207
		case cancelMessageChannel <- &cancelRequestMessage{requestID, false}:
208 209 210 211 212
			cancelMessageChannel = nil
		// clear out any remaining responses, in case and "incoming reponse"
		// messages get processed before our cancel message
		case _, ok := <-incomingResponses:
			if !ok {
213 214 215 216 217
				incomingResponses = nil
			}
		case _, ok := <-incomingErrors:
			if !ok {
				incomingErrors = nil
218 219 220 221 222 223 224 225
			}
		case <-rm.ctx.Done():
			return
		}
	}
}

type processResponseMessage struct {
226
	p         peer.ID
227 228
	responses []gsmsg.GraphSyncResponse
	blks      []blocks.Block
229 230 231 232
}

// ProcessResponses ingests the given responses from the network and
// and updates the in progress requests based on those responses.
233
func (rm *RequestManager) ProcessResponses(p peer.ID, responses []gsmsg.GraphSyncResponse,
234
	blks []blocks.Block) {
235
	select {
236
	case rm.messages <- &processResponseMessage{p, responses, blks}:
237 238 239 240
	case <-rm.ctx.Done():
	}
}

241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
type unpauseRequestMessage struct {
	id         graphsync.RequestID
	extensions []graphsync.ExtensionData
	response   chan error
}

// UnpauseRequest unpauses a request that was paused in a block hook based request ID
// Can also send extensions with unpause
func (rm *RequestManager) UnpauseRequest(requestID graphsync.RequestID, extensions ...graphsync.ExtensionData) error {
	response := make(chan error, 1)
	return rm.sendSyncMessage(&unpauseRequestMessage{requestID, extensions, response}, response)
}

type pauseRequestMessage struct {
	id       graphsync.RequestID
	response chan error
}

// PauseRequest pauses an in progress request (may take 1 or more blocks to process)
func (rm *RequestManager) PauseRequest(requestID graphsync.RequestID) error {
	response := make(chan error, 1)
	return rm.sendSyncMessage(&pauseRequestMessage{requestID, response}, response)
}

func (rm *RequestManager) sendSyncMessage(message requestManagerMessage, response chan error) error {
	select {
	case <-rm.ctx.Done():
		return errors.New("Context Cancelled")
	case rm.messages <- message:
	}
	select {
	case <-rm.ctx.Done():
		return errors.New("Context Cancelled")
	case err := <-response:
		return err
	}
}

279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
// Startup starts processing for the WantManager.
func (rm *RequestManager) Startup() {
	go rm.run()
}

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

func (rm *RequestManager) run() {
	// NOTE: Do not open any streams or connections from anywhere in this
	// event loop. Really, just don't do anything likely to block.
	defer rm.cleanupInProcessRequests()

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

func (rm *RequestManager) cleanupInProcessRequests() {
	for _, requestStatus := range rm.inProgressRequestStatuses {
306
		requestStatus.cancelFn()
307 308 309
	}
}

310
type terminateRequestMessage struct {
311
	requestID graphsync.RequestID
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 341
func (nrm *newRequestMessage) setupRequest(requestID graphsync.RequestID, rm *RequestManager) (chan graphsync.ResponseProgress, chan error) {
	request, hooksResult, err := rm.validateRequest(requestID, nrm.p, nrm.root, nrm.selector, nrm.extensions)
	if err != nil {
		return rm.singleErrorResponse(err)
	}
	doNotSendCidsData, has := request.Extension(graphsync.ExtensionDoNotSendCIDs)
	var doNotSendCids *cid.Set
	if has {
		doNotSendCids, err = cidset.DecodeCidSet(doNotSendCidsData)
		if err != nil {
			return rm.singleErrorResponse(err)
		}
	} else {
		doNotSendCids = cid.NewSet()
	}
	ctx, cancel := context.WithCancel(rm.ctx)
	p := nrm.p
	resumeMessages := make(chan []graphsync.ExtensionData, 1)
	pauseMessages := make(chan struct{}, 1)
	networkError := make(chan error, 1)
	requestStatus := &inProgressRequestStatus{
		ctx: ctx, cancelFn: cancel, p: p, resumeMessages: resumeMessages, pauseMessages: pauseMessages, networkError: networkError,
	}
	lastResponse := &requestStatus.lastResponse
	lastResponse.Store(gsmsg.NewResponse(request.ID(), graphsync.RequestAcknowledged))
	rm.inProgressRequestStatuses[request.ID()] = requestStatus
	incoming, incomingError := executor.ExecutionEnv{
		Ctx:              rm.ctx,
342
		SendRequest:      rm.sendRequest,
343 344 345 346 347
		TerminateRequest: rm.terminateRequest,
		RunBlockHooks:    rm.processBlockHooks,
		Loader:           rm.asyncLoader.AsyncLoad,
	}.Start(
		executor.RequestExecution{
hannahhoward's avatar
hannahhoward committed
348 349 350 351 352 353
			Ctx:                  ctx,
			P:                    p,
			Request:              request,
			NetworkError:         networkError,
			LastResponse:         lastResponse,
			DoNotSendCids:        doNotSendCids,
Eric Myhre's avatar
Eric Myhre committed
354
			NodePrototypeChooser: hooksResult.CustomChooser,
hannahhoward's avatar
hannahhoward committed
355 356
			ResumeMessages:       resumeMessages,
			PauseMessages:        pauseMessages,
357 358 359 360
		})
	return incoming, incomingError
}

361
func (nrm *newRequestMessage) handle(rm *RequestManager) {
Hannah Howard's avatar
Hannah Howard committed
362 363
	var ipr inProgressRequest
	ipr.requestID = rm.nextRequestID
364
	rm.nextRequestID++
365
	ipr.incoming, ipr.incomingError = nrm.setupRequest(ipr.requestID, rm)
366 367

	select {
Hannah Howard's avatar
Hannah Howard committed
368
	case nrm.inProgressRequestChan <- ipr:
369 370 371 372
	case <-rm.ctx.Done():
	}
}

373 374 375 376 377
func (trm *terminateRequestMessage) handle(rm *RequestManager) {
	delete(rm.inProgressRequestStatuses, trm.requestID)
	rm.asyncLoader.CleanupRequest(trm.requestID)
}

378 379 380 381 382 383
func (crm *cancelRequestMessage) handle(rm *RequestManager) {
	inProgressRequestStatus, ok := rm.inProgressRequestStatuses[crm.requestID]
	if !ok {
		return
	}

384
	rm.sendRequest(inProgressRequestStatus.p, gsmsg.CancelRequest(crm.requestID))
385 386 387 388 389
	if crm.isPause {
		inProgressRequestStatus.paused = true
	} else {
		inProgressRequestStatus.cancelFn()
	}
390 391 392
}

func (prm *processResponseMessage) handle(rm *RequestManager) {
393 394
	filteredResponses := rm.processExtensions(prm.responses, prm.p)
	filteredResponses = rm.filterResponsesForPeer(filteredResponses, prm.p)
Hannah Howard's avatar
Hannah Howard committed
395
	rm.updateLastResponses(filteredResponses)
396
	responseMetadata := metadataForResponses(filteredResponses)
397 398 399 400 401 402 403 404 405 406
	rm.asyncLoader.ProcessResponse(responseMetadata, prm.blks)
	rm.processTerminations(filteredResponses)
}

func (rm *RequestManager) filterResponsesForPeer(responses []gsmsg.GraphSyncResponse, p peer.ID) []gsmsg.GraphSyncResponse {
	responsesForPeer := make([]gsmsg.GraphSyncResponse, 0, len(responses))
	for _, response := range responses {
		requestStatus, ok := rm.inProgressRequestStatuses[response.RequestID()]
		if !ok || requestStatus.p != p {
			continue
407
		}
408
		responsesForPeer = append(responsesForPeer, response)
409
	}
410 411
	return responsesForPeer
}
412

413 414 415 416 417 418 419 420 421 422 423
func (rm *RequestManager) processExtensions(responses []gsmsg.GraphSyncResponse, p peer.ID) []gsmsg.GraphSyncResponse {
	remainingResponses := make([]gsmsg.GraphSyncResponse, 0, len(responses))
	for _, response := range responses {
		success := rm.processExtensionsForResponse(p, response)
		if success {
			remainingResponses = append(remainingResponses, response)
		}
	}
	return remainingResponses
}

Hannah Howard's avatar
Hannah Howard committed
424 425 426 427 428 429
func (rm *RequestManager) updateLastResponses(responses []gsmsg.GraphSyncResponse) {
	for _, response := range responses {
		rm.inProgressRequestStatuses[response.RequestID()].lastResponse.Store(response)
	}
}

430
func (rm *RequestManager) processExtensionsForResponse(p peer.ID, response gsmsg.GraphSyncResponse) bool {
Hannah Howard's avatar
Hannah Howard committed
431 432 433
	result := rm.responseHooks.ProcessResponseHooks(p, response)
	if len(result.Extensions) > 0 {
		updateRequest := gsmsg.UpdateRequest(response.RequestID(), result.Extensions...)
434
		rm.sendRequest(p, updateRequest)
Hannah Howard's avatar
Hannah Howard committed
435 436
	}
	if result.Err != nil {
437 438 439 440
		requestStatus, ok := rm.inProgressRequestStatuses[response.RequestID()]
		if !ok {
			return false
		}
Hannah Howard's avatar
Hannah Howard committed
441 442 443 444
		responseError := rm.generateResponseErrorFromStatus(graphsync.RequestFailedUnknown)
		select {
		case requestStatus.networkError <- responseError:
		case <-requestStatus.ctx.Done():
445
		}
446
		rm.sendRequest(p, gsmsg.CancelRequest(response.RequestID()))
Hannah Howard's avatar
Hannah Howard committed
447 448
		requestStatus.cancelFn()
		return false
449 450 451 452
	}
	return true
}

453 454
func (rm *RequestManager) processTerminations(responses []gsmsg.GraphSyncResponse) {
	for _, response := range responses {
455
		if gsmsg.IsTerminalResponseCode(response.Status()) {
456 457 458 459 460 461
			if gsmsg.IsTerminalFailureCode(response.Status()) {
				requestStatus := rm.inProgressRequestStatuses[response.RequestID()]
				responseError := rm.generateResponseErrorFromStatus(response.Status())
				select {
				case requestStatus.networkError <- responseError:
				case <-requestStatus.ctx.Done():
462
				}
463
				requestStatus.cancelFn()
464
			}
465
			rm.asyncLoader.CompleteResponsesFor(response.RequestID())
466 467 468
		}
	}
}
469

470
func (rm *RequestManager) generateResponseErrorFromStatus(status graphsync.ResponseStatusCode) error {
471
	switch status {
472
	case graphsync.RequestFailedBusy:
473
		return graphsync.RequestFailedBusyErr{}
474
	case graphsync.RequestFailedContentNotFound:
475
		return graphsync.RequestFailedContentNotFoundErr{}
476
	case graphsync.RequestFailedLegal:
477
		return graphsync.RequestFailedLegalErr{}
478
	case graphsync.RequestFailedUnknown:
479 480 481
		return graphsync.RequestFailedUnknownErr{}
	case graphsync.RequestCancelled:
		return graphsync.RequestCancelledErr{}
482
	default:
483
		return fmt.Errorf("Unknown")
484 485
	}
}
486

Hannah Howard's avatar
Hannah Howard committed
487 488 489 490
func (rm *RequestManager) processBlockHooks(p peer.ID, response graphsync.ResponseData, block graphsync.BlockData) error {
	result := rm.blockHooks.ProcessBlockHooks(p, response, block)
	if len(result.Extensions) > 0 {
		updateRequest := gsmsg.UpdateRequest(response.RequestID(), result.Extensions...)
491
		rm.sendRequest(p, updateRequest)
492
	}
Hannah Howard's avatar
Hannah Howard committed
493
	if result.Err != nil {
494
		_, isPause := result.Err.(hooks.ErrPaused)
Hannah Howard's avatar
Hannah Howard committed
495 496
		select {
		case <-rm.ctx.Done():
497
		case rm.messages <- &cancelRequestMessage{response.RequestID(), isPause}:
Hannah Howard's avatar
Hannah Howard committed
498
		}
499
	}
Hannah Howard's avatar
Hannah Howard committed
500 501 502
	return result.Err
}

503 504 505 506 507 508 509
func (rm *RequestManager) terminateRequest(requestID graphsync.RequestID) {
	select {
	case <-rm.ctx.Done():
	case rm.messages <- &terminateRequestMessage{requestID}:
	}
}

510
func (rm *RequestManager) validateRequest(requestID graphsync.RequestID, p peer.ID, root ipld.Link, selectorSpec ipld.Node, extensions []graphsync.ExtensionData) (gsmsg.GraphSyncRequest, hooks.RequestResult, error) {
Hannah Howard's avatar
Hannah Howard committed
511 512
	_, err := ipldutil.EncodeNode(selectorSpec)
	if err != nil {
513
		return gsmsg.GraphSyncRequest{}, hooks.RequestResult{}, err
Hannah Howard's avatar
Hannah Howard committed
514
	}
515
	_, err = ipldutil.ParseSelector(selectorSpec)
Hannah Howard's avatar
Hannah Howard committed
516
	if err != nil {
517
		return gsmsg.GraphSyncRequest{}, hooks.RequestResult{}, err
Hannah Howard's avatar
Hannah Howard committed
518 519 520
	}
	asCidLink, ok := root.(cidlink.Link)
	if !ok {
521
		return gsmsg.GraphSyncRequest{}, hooks.RequestResult{}, fmt.Errorf("request failed: link has no cid")
Hannah Howard's avatar
Hannah Howard committed
522 523 524
	}
	request := gsmsg.NewRequest(requestID, asCidLink.Cid, selectorSpec, defaultPriority, extensions...)
	hooksResult := rm.requestHooks.ProcessRequestHooks(p, request)
Hannah Howard's avatar
Hannah Howard committed
525 526 527 528 529 530 531 532 533 534 535 536
	if hooksResult.PersistenceOption != "" {
		dedupData, err := dedupkey.EncodeDedupKey(hooksResult.PersistenceOption)
		if err != nil {
			return gsmsg.GraphSyncRequest{}, hooks.RequestResult{}, err
		}
		request = request.ReplaceExtensions([]graphsync.ExtensionData{
			{
				Name: graphsync.ExtensionDeDupByKey,
				Data: dedupData,
			},
		})
	}
Hannah Howard's avatar
Hannah Howard committed
537 538
	err = rm.asyncLoader.StartRequest(requestID, hooksResult.PersistenceOption)
	if err != nil {
539
		return gsmsg.GraphSyncRequest{}, hooks.RequestResult{}, err
Hannah Howard's avatar
Hannah Howard committed
540
	}
541
	return request, hooksResult, nil
Hannah Howard's avatar
Hannah Howard committed
542
}
543

544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568
type reqSubscriber struct {
	p                     peer.ID
	request               gsmsg.GraphSyncRequest
	networkErrorListeners *listeners.NetworkErrorListeners
}

func (r *reqSubscriber) OnNext(topic notifications.Topic, event notifications.Event) {
	mqEvt, isMQEvt := event.(messagequeue.Event)
	if !isMQEvt || mqEvt.Name != messagequeue.Error {
		return
	}

	r.networkErrorListeners.NotifyNetworkErrorListeners(r.p, r.request, mqEvt.Err)
	//r.re.networkError <- mqEvt.Err
	//r.re.terminateRequest()
}

func (r reqSubscriber) OnClose(topic notifications.Topic) {
}

const requestNetworkError = "request_network_error"

func (rm *RequestManager) sendRequest(p peer.ID, request gsmsg.GraphSyncRequest) {
	sub := notifications.NewTopicDataSubscriber(&reqSubscriber{p, request, rm.networkErrorListeners})
	failNotifee := notifications.Notifee{Data: requestNetworkError, Subscriber: sub}
569 570 571
	rm.peerHandler.BuildMessage(p, 0, func(builder *gsmsg.Builder) {
		builder.AddRequest(request)
	}, []notifications.Notifee{failNotifee})
572 573
}

574 575 576 577 578 579 580 581 582 583 584
func (urm *unpauseRequestMessage) unpause(rm *RequestManager) error {
	inProgressRequestStatus, ok := rm.inProgressRequestStatuses[urm.id]
	if !ok {
		return errors.New("request not found")
	}
	if !inProgressRequestStatus.paused {
		return errors.New("request is not paused")
	}
	inProgressRequestStatus.paused = false
	select {
	case <-inProgressRequestStatus.pauseMessages:
585
		rm.sendRequest(inProgressRequestStatus.p, gsmsg.UpdateRequest(urm.id, urm.extensions...))
586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622
		return nil
	case <-rm.ctx.Done():
		return errors.New("context cancelled")
	case inProgressRequestStatus.resumeMessages <- urm.extensions:
		return nil
	}
}
func (urm *unpauseRequestMessage) handle(rm *RequestManager) {
	err := urm.unpause(rm)
	select {
	case <-rm.ctx.Done():
	case urm.response <- err:
	}
}
func (prm *pauseRequestMessage) pause(rm *RequestManager) error {
	inProgressRequestStatus, ok := rm.inProgressRequestStatuses[prm.id]
	if !ok {
		return errors.New("request not found")
	}
	if inProgressRequestStatus.paused {
		return errors.New("request is already paused")
	}
	inProgressRequestStatus.paused = true
	select {
	case <-rm.ctx.Done():
		return errors.New("context cancelled")
	case inProgressRequestStatus.pauseMessages <- struct{}{}:
		return nil
	}
}
func (prm *pauseRequestMessage) handle(rm *RequestManager) {
	err := prm.pause(rm)
	select {
	case <-rm.ctx.Done():
	case prm.response <- err:
	}
}