requestmanager.go 9.13 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
}

// PeerHandler is an interface that can send requests to peers
type PeerHandler interface {
46
	SendRequest(p peer.ID, graphSyncRequest gsmsg.GraphSyncRequest)
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
}

// 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 {
87 88 89
	requestID     gsmsg.GraphSyncRequestID
	incoming      chan ResponseProgress
	incomingError chan ResponseError
90 91 92 93 94 95 96 97 98
}

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

// SendRequest initiates a new GraphSync request to the given peer.
99 100 101
func (rm *RequestManager) SendRequest(ctx context.Context,
	p peer.ID,
	cidRootedSelector ipld.Node) (<-chan ResponseProgress, <-chan ResponseError) {
102
	if len(rm.ipldBridge.ValidateSelectorSpec(cidRootedSelector)) != 0 {
103
		return rm.singleErrorResponse(fmt.Errorf("Invalid Selector Spec"))
104 105 106 107 108 109 110
	}

	inProgressRequestChan := make(chan inProgressRequest)

	select {
	case rm.messages <- &newRequestMessage{p, cidRootedSelector, inProgressRequestChan}:
	case <-rm.ctx.Done():
111
		return rm.emptyResponse()
112
	case <-ctx.Done():
113
		return rm.emptyResponse()
114 115 116 117
	}
	var receivedInProgressRequest inProgressRequest
	select {
	case <-rm.ctx.Done():
118
		return rm.emptyResponse()
119 120 121
	case receivedInProgressRequest = <-inProgressRequestChan:
	}

122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
	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)
144
	errCh <- err
145 146
	close(errCh)
	return ch, errCh
147 148 149 150 151 152
}

type cancelRequestMessage struct {
	requestID gsmsg.GraphSyncRequestID
}

153 154 155
func (rm *RequestManager) cancelRequest(requestID gsmsg.GraphSyncRequestID,
	incomingResponses chan ResponseProgress,
	incomingErrors chan ResponseError) {
156
	cancelMessageChannel := rm.messages
157
	for cancelMessageChannel != nil || incomingResponses != nil || incomingErrors != nil {
158 159 160 161 162 163 164
		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 {
165 166 167 168 169
				incomingResponses = nil
			}
		case _, ok := <-incomingErrors:
			if !ok {
				incomingErrors = nil
170 171 172 173 174 175 176 177
			}
		case <-rm.ctx.Done():
			return
		}
	}
}

type processResponseMessage struct {
178 179
	responses []gsmsg.GraphSyncResponse
	blks      []blocks.Block
180 181 182 183
}

// ProcessResponses ingests the given responses from the network and
// and updates the in progress requests based on those responses.
184 185
func (rm *RequestManager) ProcessResponses(responses []gsmsg.GraphSyncResponse,
	blks []blocks.Block) {
186
	select {
187
	case rm.messages <- &processResponseMessage{responses, blks}:
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
	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 {
219
		requestStatus.shutdown()
220 221 222 223
	}
}

func (nrm *newRequestMessage) handle(rm *RequestManager) {
224 225 226
	var inProgressChan chan ResponseProgress
	var inProgressErr chan ResponseError

227 228 229
	requestID := rm.nextRequestID
	rm.nextRequestID++

230
	selectorBytes, err := rm.ipldBridge.EncodeNode(nrm.selector)
231
	if err != nil {
232
		inProgressChan, inProgressErr = rm.singleErrorResponse(err)
233
	} else {
234 235
		inProgressChan = make(chan ResponseProgress)
		inProgressErr = make(chan ResponseError)
236 237 238
		ctx, cancel := context.WithCancel(rm.ctx)

		rm.inProgressRequestStatuses[requestID] = &inProgressRequestStatus{
239
			ctx, cancel, nrm.p, inProgressChan, inProgressErr,
240
		}
241
		rm.peerHandler.SendRequest(nrm.p, gsmsg.NewRequest(requestID, selectorBytes, maxPriority))
242 243 244 245 246
		// not starting a traversal atm
	}

	select {
	case nrm.inProgressRequestChan <- inProgressRequest{
247 248 249
		requestID:     requestID,
		incoming:      inProgressChan,
		incomingError: inProgressErr,
250 251 252 253 254 255 256 257 258 259 260
	}:
	case <-rm.ctx.Done():
	}
}

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

261
	rm.peerHandler.SendRequest(inProgressRequestStatus.p, gsmsg.CancelRequest(crm.requestID))
262
	delete(rm.inProgressRequestStatuses, crm.requestID)
263
	inProgressRequestStatus.shutdown()
264 265 266
}

func (prm *processResponseMessage) handle(rm *RequestManager) {
267
	for _, block := range prm.blks {
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
		// 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():
			}
		}
	}

283
	for _, response := range prm.responses {
284 285 286 287
		// 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()]
288

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

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