asyncloader.go 6.26 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 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 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 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 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 231 232 233 234 235 236 237 238 239
package asyncloader

import (
	"context"
	"errors"
	"sync"

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

type loadRequest struct {
	requestID    gsmsg.GraphSyncRequestID
	link         ipld.Link
	responseChan chan []byte
	errChan      chan error
}

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

func newLoadRequest(requestID gsmsg.GraphSyncRequestID,
	link ipld.Link,
	responseChan chan []byte,
	errChan chan error) *loadRequest {
	lr := loadRequestPool.Get().(*loadRequest)
	lr.requestID = requestID
	lr.link = link
	lr.responseChan = responseChan
	lr.errChan = errChan
	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)

// 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.
func (abl *AsyncLoader) AsyncLoad(requestID gsmsg.GraphSyncRequestID, link ipld.Link) (<-chan []byte, <-chan error) {
	responseChan := make(chan []byte, 1)
	errChan := make(chan error, 1)
	lr := newLoadRequest(requestID, link, responseChan, errChan)
	select {
	case <-abl.ctx.Done():
		abl.terminateWithError("Context Closed", responseChan, errChan)
	case abl.incomingMessages <- lr:
	}
	return responseChan, errChan
}

// 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) {
	_, ok := abl.activeRequests[lr.requestID]
	if !ok {
		abl.terminateWithError("No active request", lr.responseChan, lr.errChan)
		returnLoadRequest(lr)
		return
	}
	response, err := abl.loadAttempter(lr.requestID, lr.link)
	if err != nil {
		lr.errChan <- err
		close(lr.errChan)
		close(lr.responseChan)
		returnLoadRequest(lr)
		return
	}
	if response != nil {
		lr.responseChan <- response
		close(lr.errChan)
		close(lr.responseChan)
		returnLoadRequest(lr)
		return
	}
	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 {
			abl.terminateWithError("No active request", lr.responseChan, lr.errChan)
			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:
		}
	}
}

func (abl *AsyncLoader) terminateWithError(errMsg string, responseChan chan<- []byte, errChan chan<- error) {
	errChan <- errors.New(errMsg)
	close(errChan)
	close(responseChan)
}