asyncloader.go 6.23 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12
package asyncloader

import (
	"context"
	"errors"
	"sync"

	gsmsg "github.com/ipfs/go-graphsync/message"
	"github.com/ipld/go-ipld-prime"
)

type loadRequest struct {
13 14 15
	requestID  gsmsg.GraphSyncRequestID
	link       ipld.Link
	resultChan chan AsyncLoadResult
16 17 18 19 20 21 22 23 24 25
}

var loadRequestPool = sync.Pool{
	New: func() interface{} {
		return new(loadRequest)
	},
}

func newLoadRequest(requestID gsmsg.GraphSyncRequestID,
	link ipld.Link,
26
	resultChan chan AsyncLoadResult) *loadRequest {
27 28 29
	lr := loadRequestPool.Get().(*loadRequest)
	lr.requestID = requestID
	lr.link = link
30
	lr.resultChan = resultChan
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
	return lr
}

func returnLoadRequest(lr *loadRequest) {
	*lr = loadRequest{}
	loadRequestPool.Put(lr)
}

type loaderMessage interface {
	handle(abl *AsyncLoader)
}

type newResponsesAvailableMessage struct{}

type startRequestMessage struct {
	requestID gsmsg.GraphSyncRequestID
}

type finishRequestMessage struct {
	requestID gsmsg.GraphSyncRequestID
}

// LoadAttempter attempts to load a link to an array of bytes
// it has three results:
// bytes present, error nil = success
// bytes nil, error present = error
// bytes nil, error nil = did not load, but try again later
type LoadAttempter func(gsmsg.GraphSyncRequestID, ipld.Link) ([]byte, error)

60 61 62 63 64 65
// AsyncLoadResult is sent once over the channel returned by an async load.
type AsyncLoadResult struct {
	Data []byte
	Err  error
}

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
// AsyncLoader is used to make multiple attempts to load a blocks over the
// course of a request - as long as a request is in progress, it will make multiple
// attempts to load a block until it gets a definitive result of whether the block
// is present or missing in the response
type AsyncLoader struct {
	ctx              context.Context
	cancel           context.CancelFunc
	loadAttempter    LoadAttempter
	incomingMessages chan loaderMessage
	outgoingMessages chan loaderMessage
	activeRequests   map[gsmsg.GraphSyncRequestID]struct{}
	pausedRequests   []*loadRequest
}

// New initializes a new AsyncLoader from the given context and loadAttempter function
func New(ctx context.Context, loadAttempter LoadAttempter) *AsyncLoader {
	ctx, cancel := context.WithCancel(ctx)
	return &AsyncLoader{
		ctx:              ctx,
		cancel:           cancel,
		loadAttempter:    loadAttempter,
		incomingMessages: make(chan loaderMessage),
		outgoingMessages: make(chan loaderMessage),
		activeRequests:   make(map[gsmsg.GraphSyncRequestID]struct{}),
	}
}

// AsyncLoad asynchronously loads the given link for the given request ID. It returns a channel for data and a channel
// for errors -- only one message will be sent over either.
95 96 97
func (abl *AsyncLoader) AsyncLoad(requestID gsmsg.GraphSyncRequestID, link ipld.Link) <-chan AsyncLoadResult {
	resultChan := make(chan AsyncLoadResult, 1)
	lr := newLoadRequest(requestID, link, resultChan)
98 99
	select {
	case <-abl.ctx.Done():
100
		abl.terminateWithError("Context Closed", resultChan)
101 102
	case abl.incomingMessages <- lr:
	}
103
	return resultChan
104 105 106 107 108 109 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 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
}

// NewResponsesAvailable indicates that the async loader should make another attempt to load
// the links that are currently pending.
func (abl *AsyncLoader) NewResponsesAvailable() {
	select {
	case <-abl.ctx.Done():
	case abl.incomingMessages <- &newResponsesAvailableMessage{}:
	}
}

// StartRequest indicates the given request has started and the loader should
// accepting link load requests for this requestID.
func (abl *AsyncLoader) StartRequest(requestID gsmsg.GraphSyncRequestID) {
	select {
	case <-abl.ctx.Done():
	case abl.incomingMessages <- &startRequestMessage{requestID}:
	}
}

// FinishRequest indicates the given request is completed or cancelled, and all in
// progress link load requests for this request ID should error
func (abl *AsyncLoader) FinishRequest(requestID gsmsg.GraphSyncRequestID) {
	select {
	case <-abl.ctx.Done():
	case abl.incomingMessages <- &finishRequestMessage{requestID}:
	}
}

// Startup starts processing of messages
func (abl *AsyncLoader) Startup() {
	go abl.messageQueueWorker()
	go abl.run()
}

// Shutdown stops processing of messages
func (abl *AsyncLoader) Shutdown() {
	abl.cancel()
}

func (abl *AsyncLoader) run() {
	for {
		select {
		case <-abl.ctx.Done():
			return
		case message := <-abl.outgoingMessages:
			message.handle(abl)
		}
	}
}

func (abl *AsyncLoader) messageQueueWorker() {
	var messageBuffer []loaderMessage
	nextMessage := func() loaderMessage {
		if len(messageBuffer) == 0 {
			return nil
		}
		return messageBuffer[0]
	}
	outgoingMessages := func() chan<- loaderMessage {
		if len(messageBuffer) == 0 {
			return nil
		}
		return abl.outgoingMessages
	}
	for {
		select {
		case incomingMessage := <-abl.incomingMessages:
			messageBuffer = append(messageBuffer, incomingMessage)
		case outgoingMessages() <- nextMessage():
			messageBuffer = messageBuffer[1:]
		case <-abl.ctx.Done():
			return
		}
	}
}

func (lr *loadRequest) handle(abl *AsyncLoader) {
	response, err := abl.loadAttempter(lr.requestID, lr.link)
	if err != nil {
184 185
		lr.resultChan <- AsyncLoadResult{nil, err}
		close(lr.resultChan)
186 187 188 189
		returnLoadRequest(lr)
		return
	}
	if response != nil {
190 191
		lr.resultChan <- AsyncLoadResult{response, nil}
		close(lr.resultChan)
192 193 194
		returnLoadRequest(lr)
		return
	}
195 196 197 198 199 200
	_, ok := abl.activeRequests[lr.requestID]
	if !ok {
		abl.terminateWithError("No active request", lr.resultChan)
		returnLoadRequest(lr)
		return
	}
201 202 203 204 205 206 207 208 209 210 211 212 213
	abl.pausedRequests = append(abl.pausedRequests, lr)
}

func (srm *startRequestMessage) handle(abl *AsyncLoader) {
	abl.activeRequests[srm.requestID] = struct{}{}
}

func (frm *finishRequestMessage) handle(abl *AsyncLoader) {
	delete(abl.activeRequests, frm.requestID)
	pausedRequests := abl.pausedRequests
	abl.pausedRequests = nil
	for _, lr := range pausedRequests {
		if lr.requestID == frm.requestID {
214
			abl.terminateWithError("No active request", lr.resultChan)
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
			returnLoadRequest(lr)
		} else {
			abl.pausedRequests = append(abl.pausedRequests, lr)
		}
	}
}

func (nram *newResponsesAvailableMessage) handle(abl *AsyncLoader) {
	// drain buffered
	pausedRequests := abl.pausedRequests
	abl.pausedRequests = nil
	for _, lr := range pausedRequests {
		select {
		case <-abl.ctx.Done():
			return
		case abl.incomingMessages <- lr:
		}
	}
}

235 236 237
func (abl *AsyncLoader) terminateWithError(errMsg string, resultChan chan<- AsyncLoadResult) {
	resultChan <- AsyncLoadResult{nil, errors.New(errMsg)}
	close(resultChan)
238
}