requestmanager.go 9.16 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
// ResponseError is an error that occurred during a traversal.
23
type ResponseError error
24

25 26 27 28 29 30 31 32 33 34
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
35 36 37 38 39 40 41
	errorChannel    chan ResponseError
}

func (ipr *inProgressRequestStatus) shutdown() {
	close(ipr.responseChannel)
	close(ipr.errorChannel)
	ipr.cancelFn()
42 43 44 45 46 47 48 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
}

// 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 {
94 95 96
	requestID     gsmsg.GraphSyncRequestID
	incoming      chan ResponseProgress
	incomingError chan ResponseError
97 98 99 100 101 102 103 104 105
}

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

// SendRequest initiates a new GraphSync request to the given peer.
106 107 108
func (rm *RequestManager) SendRequest(ctx context.Context,
	p peer.ID,
	cidRootedSelector ipld.Node) (<-chan ResponseProgress, <-chan ResponseError) {
109
	if len(rm.ipldBridge.ValidateSelectorSpec(cidRootedSelector)) != 0 {
110
		return rm.singleErrorResponse(fmt.Errorf("Invalid Selector Spec"))
111 112 113 114 115 116 117
	}

	inProgressRequestChan := make(chan inProgressRequest)

	select {
	case rm.messages <- &newRequestMessage{p, cidRootedSelector, inProgressRequestChan}:
	case <-rm.ctx.Done():
118
		return rm.emptyResponse()
119
	case <-ctx.Done():
120
		return rm.emptyResponse()
121 122 123 124
	}
	var receivedInProgressRequest inProgressRequest
	select {
	case <-rm.ctx.Done():
125
		return rm.emptyResponse()
126 127 128
	case receivedInProgressRequest = <-inProgressRequestChan:
	}

129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
	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)
151
	errCh <- err
152 153
	close(errCh)
	return ch, errCh
154 155 156 157 158 159
}

type cancelRequestMessage struct {
	requestID gsmsg.GraphSyncRequestID
}

160 161 162
func (rm *RequestManager) cancelRequest(requestID gsmsg.GraphSyncRequestID,
	incomingResponses chan ResponseProgress,
	incomingErrors chan ResponseError) {
163
	cancelMessageChannel := rm.messages
164
	for cancelMessageChannel != nil || incomingResponses != nil || incomingErrors != nil {
165 166 167 168 169 170 171
		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 {
172 173 174 175 176
				incomingResponses = nil
			}
		case _, ok := <-incomingErrors:
			if !ok {
				incomingErrors = nil
177 178 179 180 181 182 183 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
			}
		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 {
224
		requestStatus.shutdown()
225 226 227 228
	}
}

func (nrm *newRequestMessage) handle(rm *RequestManager) {
229 230 231
	var inProgressChan chan ResponseProgress
	var inProgressErr chan ResponseError

232 233 234
	requestID := rm.nextRequestID
	rm.nextRequestID++

235
	selectorBytes, err := rm.ipldBridge.EncodeNode(nrm.selector)
236
	if err != nil {
237
		inProgressChan, inProgressErr = rm.singleErrorResponse(err)
238
	} else {
239 240
		inProgressChan = make(chan ResponseProgress)
		inProgressErr = make(chan ResponseError)
241 242 243
		ctx, cancel := context.WithCancel(rm.ctx)

		rm.inProgressRequestStatuses[requestID] = &inProgressRequestStatus{
244
			ctx, cancel, nrm.p, inProgressChan, inProgressErr,
245 246 247 248 249 250 251
		}
		rm.peerHandler.SendRequest(nrm.p, requestID, selectorBytes, maxPriority)
		// not starting a traversal atm
	}

	select {
	case nrm.inProgressRequestChan <- inProgressRequest{
252 253 254
		requestID:     requestID,
		incoming:      inProgressChan,
		incomingError: inProgressErr,
255 256 257 258 259 260 261 262 263 264 265 266 267
	}:
	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)
268
	inProgressRequestStatus.shutdown()
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
}

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()]
293

294
			if ok {
295 296 297 298 299 300 301 302
				if gsmsg.IsTerminalFailureCode(response.Status()) {
					responseError := rm.generateResponseErrorFromStatus(response.Status())
					select {
					case requestStatus.errorChannel <- responseError:
					case <-rm.ctx.Done():
					case <-requestStatus.ctx.Done():
					}
				}
303
				delete(rm.inProgressRequestStatuses, response.RequestID())
304
				requestStatus.shutdown()
305 306 307 308
			}
		}
	}
}
309 310 311 312

func (rm *RequestManager) generateResponseErrorFromStatus(status gsmsg.GraphSyncResponseStatusCode) ResponseError {
	switch status {
	case gsmsg.RequestFailedBusy:
313
		return fmt.Errorf("Request Failed - Peer Is Busy")
314
	case gsmsg.RequestFailedContentNotFound:
315
		return fmt.Errorf("Request Failed - Content Not Found")
316
	case gsmsg.RequestFailedLegal:
317
		return fmt.Errorf("Request Failed - For Legal Reasons")
318
	case gsmsg.RequestFailedUnknown:
319
		return fmt.Errorf("Request Failed - Unknown Reason")
320
	default:
321
		return fmt.Errorf("Unknown")
322 323
	}
}