requestmanager.go 9.48 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
package requestmanager

import (
	"context"
	"fmt"
	"math"

	"github.com/ipfs/go-block-format"

	"github.com/ipld/go-ipld-prime"

	ipldbridge "github.com/ipfs/go-graphsync/ipldbridge"
	gsmsg "github.com/ipfs/go-graphsync/message"
	peer "github.com/libp2p/go-libp2p-peer"
)

// ResponseProgress is the fundamental unit of responses making progress in
// the RequestManager. Still not sure about this one? Nodes? Blocks? Struct w/ error? more info?
// for now, it's just a block.
type ResponseProgress = blocks.Block

22 23 24 25 26 27 28 29 30 31
// ResponseError is an error that occurred during a traversal.
// It can be either a "non-terminal" error -- meaning progress will
// continue to happen in the future.
// or it can be a terminal error, meaning no further progress or errors
// will emit.
type ResponseError struct {
	IsTerminal bool
	Error      error
}

32 33 34 35 36 37 38 39 40 41
const (
	// maxPriority is the max priority as defined by the bitswap protocol
	maxPriority = gsmsg.GraphSyncPriority(math.MaxInt32)
)

type inProgressRequestStatus struct {
	ctx             context.Context
	cancelFn        func()
	p               peer.ID
	responseChannel chan ResponseProgress
42 43 44 45 46 47 48
	errorChannel    chan ResponseError
}

func (ipr *inProgressRequestStatus) shutdown() {
	close(ipr.responseChannel)
	close(ipr.errorChannel)
	ipr.cancelFn()
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
}

// PeerHandler is an interface that can send requests to peers
type PeerHandler interface {
	SendRequest(
		p peer.ID,
		id gsmsg.GraphSyncRequestID,
		selector []byte,
		priority gsmsg.GraphSyncPriority)
	CancelRequest(
		p peer.ID,
		id gsmsg.GraphSyncRequestID)
}

// RequestManager tracks outgoing requests and processes incoming reponses
// to them.
type RequestManager struct {
	ctx         context.Context
	cancel      func()
	messages    chan requestManagerMessage
	ipldBridge  ipldbridge.IPLDBridge
	peerHandler PeerHandler
	rc          *responseCollector

	// dont touch out side of run loop
	nextRequestID             gsmsg.GraphSyncRequestID
	inProgressRequestStatuses map[gsmsg.GraphSyncRequestID]*inProgressRequestStatus
}

type requestManagerMessage interface {
	handle(rm *RequestManager)
}

// New generates a new request manager from a context, network, and selectorQuerier
func New(ctx context.Context, ipldBridge ipldbridge.IPLDBridge) *RequestManager {
	ctx, cancel := context.WithCancel(ctx)
	return &RequestManager{
		ctx:                       ctx,
		cancel:                    cancel,
		ipldBridge:                ipldBridge,
		rc:                        newResponseCollector(ctx),
		messages:                  make(chan requestManagerMessage, 16),
		inProgressRequestStatuses: make(map[gsmsg.GraphSyncRequestID]*inProgressRequestStatus),
	}
}

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

type inProgressRequest struct {
101 102 103
	requestID     gsmsg.GraphSyncRequestID
	incoming      chan ResponseProgress
	incomingError chan ResponseError
104 105 106 107 108 109 110 111 112
}

type newRequestMessage struct {
	p                     peer.ID
	selector              ipld.Node
	inProgressRequestChan chan<- inProgressRequest
}

// SendRequest initiates a new GraphSync request to the given peer.
113 114 115
func (rm *RequestManager) SendRequest(ctx context.Context,
	p peer.ID,
	cidRootedSelector ipld.Node) (<-chan ResponseProgress, <-chan ResponseError) {
116
	if len(rm.ipldBridge.ValidateSelectorSpec(cidRootedSelector)) != 0 {
117
		return rm.singleErrorResponse(fmt.Errorf("Invalid Selector Spec"))
118 119 120 121 122 123 124
	}

	inProgressRequestChan := make(chan inProgressRequest)

	select {
	case rm.messages <- &newRequestMessage{p, cidRootedSelector, inProgressRequestChan}:
	case <-rm.ctx.Done():
125
		return rm.emptyResponse()
126
	case <-ctx.Done():
127
		return rm.emptyResponse()
128 129 130 131
	}
	var receivedInProgressRequest inProgressRequest
	select {
	case <-rm.ctx.Done():
132
		return rm.emptyResponse()
133 134 135
	case receivedInProgressRequest = <-inProgressRequestChan:
	}

136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
	return rm.rc.collectResponses(ctx,
		receivedInProgressRequest.incoming,
		receivedInProgressRequest.incomingError,
		func() {
			rm.cancelRequest(receivedInProgressRequest.requestID,
				receivedInProgressRequest.incoming,
				receivedInProgressRequest.incomingError)
		})
}

func (rm *RequestManager) emptyResponse() (chan ResponseProgress, chan ResponseError) {
	ch := make(chan ResponseProgress)
	close(ch)
	errCh := make(chan ResponseError)
	close(errCh)
	return ch, errCh
}

func (rm *RequestManager) singleErrorResponse(err error) (chan ResponseProgress, chan ResponseError) {
	ch := make(chan ResponseProgress)
	close(ch)
	errCh := make(chan ResponseError, 1)
	errCh <- ResponseError{true, err}
	close(errCh)
	return ch, errCh
161 162 163 164 165 166
}

type cancelRequestMessage struct {
	requestID gsmsg.GraphSyncRequestID
}

167 168 169
func (rm *RequestManager) cancelRequest(requestID gsmsg.GraphSyncRequestID,
	incomingResponses chan ResponseProgress,
	incomingErrors chan ResponseError) {
170
	cancelMessageChannel := rm.messages
171
	for cancelMessageChannel != nil || incomingResponses != nil || incomingErrors != nil {
172 173 174 175 176 177 178
		select {
		case cancelMessageChannel <- &cancelRequestMessage{requestID}:
			cancelMessageChannel = nil
		// clear out any remaining responses, in case and "incoming reponse"
		// messages get processed before our cancel message
		case _, ok := <-incomingResponses:
			if !ok {
179 180 181 182 183
				incomingResponses = nil
			}
		case _, ok := <-incomingErrors:
			if !ok {
				incomingErrors = nil
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
			}
		case <-rm.ctx.Done():
			return
		}
	}
}

type processResponseMessage struct {
	message gsmsg.GraphSyncMessage
}

// ProcessResponses ingests the given responses from the network and
// and updates the in progress requests based on those responses.
func (rm *RequestManager) ProcessResponses(message gsmsg.GraphSyncMessage) {
	select {
	case rm.messages <- &processResponseMessage{message}:
	case <-rm.ctx.Done():
	}
}

// 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 {
231
		requestStatus.shutdown()
232 233 234 235
	}
}

func (nrm *newRequestMessage) handle(rm *RequestManager) {
236 237 238
	var inProgressChan chan ResponseProgress
	var inProgressErr chan ResponseError

239 240 241
	requestID := rm.nextRequestID
	rm.nextRequestID++

242
	selectorBytes, err := rm.ipldBridge.EncodeNode(nrm.selector)
243
	if err != nil {
244
		inProgressChan, inProgressErr = rm.singleErrorResponse(err)
245
	} else {
246 247
		inProgressChan = make(chan ResponseProgress)
		inProgressErr = make(chan ResponseError)
248 249 250
		ctx, cancel := context.WithCancel(rm.ctx)

		rm.inProgressRequestStatuses[requestID] = &inProgressRequestStatus{
251
			ctx, cancel, nrm.p, inProgressChan, inProgressErr,
252 253 254 255 256 257 258
		}
		rm.peerHandler.SendRequest(nrm.p, requestID, selectorBytes, maxPriority)
		// not starting a traversal atm
	}

	select {
	case nrm.inProgressRequestChan <- inProgressRequest{
259 260 261
		requestID:     requestID,
		incoming:      inProgressChan,
		incomingError: inProgressErr,
262 263 264 265 266 267 268 269 270 271 272 273 274
	}:
	case <-rm.ctx.Done():
	}
}

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

	rm.peerHandler.CancelRequest(inProgressRequestStatus.p, crm.requestID)
	delete(rm.inProgressRequestStatuses, crm.requestID)
275
	inProgressRequestStatus.shutdown()
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
}

func (prm *processResponseMessage) handle(rm *RequestManager) {
	for _, block := range prm.message.Blocks() {
		// dispatch every received block to every in flight request
		// this is completely a temporary implementation
		// meant to demonstrate we can produce a round trip of blocks
		// the future implementation will actual have a temporary block store
		// and will only dispatch to those requests whose selection transversal
		// actually requires them
		for _, requestStatus := range rm.inProgressRequestStatuses {
			select {
			case requestStatus.responseChannel <- block:
			case <-rm.ctx.Done():
			case <-requestStatus.ctx.Done():
			}
		}
	}

	for _, response := range prm.message.Responses() {
		// we're keeping it super light for now -- basically just ignoring
		// reason for termination and closing the channel
		if gsmsg.IsTerminalResponseCode(response.Status()) {
			requestStatus, ok := rm.inProgressRequestStatuses[response.RequestID()]
300

301
			if ok {
302 303 304 305 306 307 308 309
				if gsmsg.IsTerminalFailureCode(response.Status()) {
					responseError := rm.generateResponseErrorFromStatus(response.Status())
					select {
					case requestStatus.errorChannel <- responseError:
					case <-rm.ctx.Done():
					case <-requestStatus.ctx.Done():
					}
				}
310
				delete(rm.inProgressRequestStatuses, response.RequestID())
311
				requestStatus.shutdown()
312 313 314 315
			}
		}
	}
}
316 317 318 319 320 321 322 323 324 325 326 327 328 329 330

func (rm *RequestManager) generateResponseErrorFromStatus(status gsmsg.GraphSyncResponseStatusCode) ResponseError {
	switch status {
	case gsmsg.RequestFailedBusy:
		return ResponseError{true, fmt.Errorf("Request Failed - Peer Is Busy")}
	case gsmsg.RequestFailedContentNotFound:
		return ResponseError{true, fmt.Errorf("Request Failed - Content Not Found")}
	case gsmsg.RequestFailedLegal:
		return ResponseError{true, fmt.Errorf("Request Failed - For Legal Reasons")}
	case gsmsg.RequestFailedUnknown:
		return ResponseError{true, fmt.Errorf("Request Failed - Unknown Reason")}
	default:
		return ResponseError{}
	}
}