responsemanager.go 7.51 KB
Newer Older
1 2 3 4 5 6
package responsemanager

import (
	"context"
	"time"

7
	cid "github.com/ipfs/go-cid"
8
	"github.com/ipfs/go-graphsync"
9 10
	"github.com/ipfs/go-graphsync/ipldbridge"
	gsmsg "github.com/ipfs/go-graphsync/message"
11
	"github.com/ipfs/go-graphsync/responsemanager/loader"
12
	"github.com/ipfs/go-graphsync/responsemanager/peerresponsemanager"
13
	"github.com/ipfs/go-peertaskqueue/peertask"
14 15
	ipld "github.com/ipld/go-ipld-prime"
	cidlink "github.com/ipld/go-ipld-prime/linking/cid"
16
	"github.com/libp2p/go-libp2p-core/peer"
17 18 19 20 21 22 23 24 25 26
)

const (
	maxInProcessRequests = 6
	thawSpeed            = time.Millisecond * 100
)

type inProgressResponseStatus struct {
	ctx      context.Context
	cancelFn func()
27
	root     cid.Cid
28 29 30 31 32
	selector []byte
}

type responseKey struct {
	p         peer.ID
33
	requestID graphsync.RequestID
34 35 36 37
}

type responseTaskData struct {
	ctx      context.Context
38
	root     cid.Cid
39 40 41 42 43 44
	selector []byte
}

// QueryQueue is an interface that can receive new selector query tasks
// and prioritize them as needed, and pop them off later
type QueryQueue interface {
Dirk McCormick's avatar
Dirk McCormick committed
45 46 47 48
	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)
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 101 102 103 104
	ThawRound()
}

// 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 {
	ctx         context.Context
	cancelFn    context.CancelFunc
	loader      ipldbridge.Loader
	ipldBridge  ipldbridge.IPLDBridge
	peerManager PeerManager
	queryQueue  QueryQueue

	messages            chan responseManagerMessage
	workSignal          chan struct{}
	ticker              *time.Ticker
	inProgressResponses map[responseKey]inProgressResponseStatus
}

// New creates a new response manager from the given context, loader,
// bridge to IPLD interface, peerManager, and queryQueue.
func New(ctx context.Context,
	loader ipldbridge.Loader,
	ipldBridge ipldbridge.IPLDBridge,
	peerManager PeerManager,
	queryQueue QueryQueue) *ResponseManager {
	ctx, cancelFn := context.WithCancel(ctx)
	return &ResponseManager{
		ctx:                 ctx,
		cancelFn:            cancelFn,
		loader:              loader,
		ipldBridge:          ipldBridge,
		peerManager:         peerManager,
		queryQueue:          queryQueue,
		messages:            make(chan responseManagerMessage, 16),
		workSignal:          make(chan struct{}, 1),
		ticker:              time.NewTicker(thawSpeed),
		inProgressResponses: make(map[responseKey]inProgressResponseStatus),
	}
}

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

// ProcessRequests processes incoming requests for the given peer
105
func (rm *ResponseManager) ProcessRequests(ctx context.Context, p peer.ID, requests []gsmsg.GraphSyncRequest) {
106 107 108
	select {
	case rm.messages <- &processRequestMessage{p, requests}:
	case <-rm.ctx.Done():
109
	case <-ctx.Done():
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
	}
}

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
}

type finishResponseRequest struct {
	key responseKey
}

func (rm *ResponseManager) processQueriesWorker() {
	taskDataChan := make(chan *responseTaskData)
	var taskData *responseTaskData
	for {
Dirk McCormick's avatar
Dirk McCormick committed
143 144
		p, nextTasks, _ := rm.queryQueue.PopTasks(1)
		for nextTasks == nil {
145 146 147 148
			select {
			case <-rm.ctx.Done():
				return
			case <-rm.workSignal:
Dirk McCormick's avatar
Dirk McCormick committed
149
				p, nextTasks, _ = rm.queryQueue.PopTasks(1)
150 151
			case <-rm.ticker.C:
				rm.queryQueue.ThawRound()
Dirk McCormick's avatar
Dirk McCormick committed
152
				p, nextTasks, _ = rm.queryQueue.PopTasks(1)
153 154
			}
		}
Dirk McCormick's avatar
Dirk McCormick committed
155 156
		for _, task := range nextTasks {
			key := task.Topic.(responseKey)
157 158 159 160 161 162 163 164 165 166
			select {
			case rm.messages <- &responseDataRequest{key, taskDataChan}:
			case <-rm.ctx.Done():
				return
			}
			select {
			case taskData = <-taskDataChan:
			case <-rm.ctx.Done():
				return
			}
167
			rm.executeQuery(taskData.ctx, key.p, key.requestID, taskData.root, taskData.selector)
168 169 170 171 172
			select {
			case rm.messages <- &finishResponseRequest{key}:
			case <-rm.ctx.Done():
			}
		}
Dirk McCormick's avatar
Dirk McCormick committed
173
		rm.queryQueue.TasksDone(p, nextTasks...)
174 175 176 177
	}

}

178
func noopVisitor(tp ipldbridge.TraversalProgress, n ipld.Node, tr ipldbridge.TraversalReason) error {
179 180 181 182 183
	return nil
}

func (rm *ResponseManager) executeQuery(ctx context.Context,
	p peer.ID,
184
	requestID graphsync.RequestID,
185 186
	root cid.Cid,
	selectorBytes []byte) {
187
	peerResponseSender := rm.peerManager.SenderForPeer(p)
188
	selectorSpec, err := rm.ipldBridge.DecodeNode(selectorBytes)
189
	if err != nil {
190
		peerResponseSender.FinishWithError(requestID, graphsync.RequestFailedUnknown)
191 192
		return
	}
193 194
	rootLink := cidlink.Link{Cid: root}
	selector, err := rm.ipldBridge.ParseSelector(selectorSpec)
195
	if err != nil {
196
		peerResponseSender.FinishWithError(requestID, graphsync.RequestFailedUnknown)
197 198 199
		return
	}
	wrappedLoader := loader.WrapLoader(rm.loader, requestID, peerResponseSender)
200
	err = rm.ipldBridge.Traverse(ctx, wrappedLoader, rootLink, selector, noopVisitor)
201
	if err != nil {
202
		peerResponseSender.FinishWithError(requestID, graphsync.RequestFailedUnknown)
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 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
		return
	}
	peerResponseSender.FinishRequest(requestID)
}

// 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] =
				inProgressResponseStatus{
					ctx:      ctx,
					cancelFn: cancelFn,
249
					root:     request.Root(),
250 251
					selector: request.Selector(),
				}
Dirk McCormick's avatar
Dirk McCormick committed
252 253 254 255 256
			rm.queryQueue.PushTasks(prm.p, peertask.Task{
				Topic:    key,
				Priority: int(request.Priority()),
				Work:     1,
			})
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
			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 {
275
		taskData = &responseTaskData{response.ctx, response.root, response.selector}
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
	} else {
		taskData = nil
	}
	select {
	case <-rm.ctx.Done():
	case rdr.taskDataChan <- taskData:
	}
}

func (frr *finishResponseRequest) handle(rm *ResponseManager) {
	response, ok := rm.inProgressResponses[frr.key]
	if !ok {
		return
	}
	delete(rm.inProgressResponses, frr.key)
	response.cancelFn()
}

func (sm *synchronizeMessage) handle(rm *ResponseManager) {
	select {
	case <-rm.ctx.Done():
	case sm.sync <- struct{}{}:
	}
}