executor.go 7.3 KB
Newer Older
1 2 3
package executor

import (
4
	"bytes"
5
	"context"
6 7
	"strings"
	"sync/atomic"
8

9
	"github.com/ipfs/go-cid"
10
	"github.com/ipfs/go-graphsync"
11
	"github.com/ipfs/go-graphsync/cidset"
12 13
	"github.com/ipfs/go-graphsync/ipldutil"
	gsmsg "github.com/ipfs/go-graphsync/message"
14 15
	"github.com/ipfs/go-graphsync/requestmanager/hooks"
	"github.com/ipfs/go-graphsync/requestmanager/types"
16 17 18
	ipld "github.com/ipld/go-ipld-prime"
	cidlink "github.com/ipld/go-ipld-prime/linking/cid"
	"github.com/ipld/go-ipld-prime/traversal"
19
	peer "github.com/libp2p/go-libp2p-core/peer"
20 21
)

22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
// AsyncLoadFn is a function which given a request id and an ipld.Link, returns
// a channel which will eventually return data for the link or an err
type AsyncLoadFn func(graphsync.RequestID, ipld.Link) <-chan types.AsyncLoadResult

// ExecutionEnv are request parameters that last between requests
type ExecutionEnv struct {
	Ctx              context.Context
	SendRequest      func(peer.ID, gsmsg.GraphSyncRequest)
	RunBlockHooks    func(p peer.ID, response graphsync.ResponseData, blk graphsync.BlockData) error
	TerminateRequest func(graphsync.RequestID)
	WaitForMessages  func(ctx context.Context, resumeMessages chan graphsync.ExtensionData) ([]graphsync.ExtensionData, error)
	Loader           AsyncLoadFn
}

// RequestExecution are parameters for a single request execution
37
type RequestExecution struct {
38 39 40
	Ctx              context.Context
	P                peer.ID
	NetworkError     chan error
41
	Request          gsmsg.GraphSyncRequest
42 43
	LastResponse     *atomic.Value
	DoNotSendCids    *cid.Set
44
	NodeStyleChooser traversal.LinkTargetNodeStyleChooser
45 46
	ResumeMessages   chan []graphsync.ExtensionData
	PauseMessages    chan struct{}
47 48 49
}

// Start begins execution of a request in a go routine
50
func (ee ExecutionEnv) Start(re RequestExecution) (chan graphsync.ResponseProgress, chan error) {
51 52 53
	executor := &requestExecutor{
		inProgressChan:   make(chan graphsync.ResponseProgress),
		inProgressErr:    make(chan error),
54 55 56
		ctx:              re.Ctx,
		p:                re.P,
		networkError:     re.NetworkError,
57
		request:          re.Request,
58 59
		lastResponse:     re.LastResponse,
		doNotSendCids:    re.DoNotSendCids,
60
		nodeStyleChooser: re.NodeStyleChooser,
61 62 63
		resumeMessages:   re.ResumeMessages,
		pauseMessages:    re.PauseMessages,
		env:              ee,
64 65 66 67 68 69 70
	}
	executor.sendRequest(executor.request)
	go executor.run()
	return executor.inProgressChan, executor.inProgressErr
}

type requestExecutor struct {
71 72 73 74 75 76 77 78 79 80 81 82 83 84
	inProgressChan    chan graphsync.ResponseProgress
	inProgressErr     chan error
	ctx               context.Context
	p                 peer.ID
	networkError      chan error
	request           gsmsg.GraphSyncRequest
	lastResponse      *atomic.Value
	nodeStyleChooser  traversal.LinkTargetNodeStyleChooser
	resumeMessages    chan []graphsync.ExtensionData
	pauseMessages     chan struct{}
	doNotSendCids     *cid.Set
	env               ExecutionEnv
	restartNeeded     bool
	pendingExtensions []graphsync.ExtensionData
85 86 87 88 89 90 91 92 93 94 95 96 97 98
}

func (re *requestExecutor) visitor(tp traversal.Progress, node ipld.Node, tr traversal.VisitReason) error {
	select {
	case <-re.ctx.Done():
	case re.inProgressChan <- graphsync.ResponseProgress{
		Node:      node,
		Path:      tp.Path,
		LastBlock: tp.LastBlock,
	}:
	}
	return nil
}

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
func (re *requestExecutor) traverse() error {
	traverser := ipldutil.TraversalBuilder{
		Root:     cidlink.Link{Cid: re.request.Root()},
		Selector: re.request.Selector(),
		Visitor:  re.visitor,
		Chooser:  re.nodeStyleChooser,
	}.Start(re.ctx)
	defer traverser.Shutdown(context.Background())
	for {
		isComplete, err := traverser.IsComplete()
		if isComplete {
			return err
		}
		lnk, _ := traverser.CurrentRequest()
		resultChan := re.env.Loader(re.request.ID(), lnk)
		var result types.AsyncLoadResult
		select {
		case result = <-resultChan:
		default:
			err := re.sendRestartAsNeeded()
			if err != nil {
				return err
			}
			select {
			case <-re.ctx.Done():
				return ipldutil.ContextCancelError{}
			case result = <-resultChan:
			}
		}
		err = re.processResult(traverser, lnk, result)
		if _, ok := err.(hooks.ErrPaused); ok {
			err = re.waitForResume()
			if err != nil {
				return err
			}
			err = traverser.Advance(bytes.NewReader(result.Data))
			if err != nil {
				return err
			}
		} else if err != nil {
			return err
		}
	}
}

144
func (re *requestExecutor) run() {
145
	err := re.traverse()
146
	if err != nil {
147
		if !isContextErr(err) {
148 149 150 151 152 153
			select {
			case <-re.ctx.Done():
			case re.inProgressErr <- err:
			}
		}
	}
154 155 156 157 158 159 160 161
	select {
	case networkError := <-re.networkError:
		select {
		case re.inProgressErr <- networkError:
		case <-re.env.Ctx.Done():
		}
	default:
	}
162 163 164 165
	re.terminateRequest()
	close(re.inProgressChan)
	close(re.inProgressErr)
}
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 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273

func (re *requestExecutor) sendRequest(request gsmsg.GraphSyncRequest) {
	re.env.SendRequest(re.p, request)
}

func (re *requestExecutor) terminateRequest() {
	re.env.TerminateRequest(re.request.ID())
}

func (re *requestExecutor) runBlockHooks(blk graphsync.BlockData) error {
	response := re.lastResponse.Load().(gsmsg.GraphSyncResponse)
	return re.env.RunBlockHooks(re.p, response, blk)
}

func (re *requestExecutor) waitForResume() error {
	select {
	case <-re.ctx.Done():
		return ipldutil.ContextCancelError{}
	case re.pendingExtensions = <-re.resumeMessages:
		re.restartNeeded = true
		return nil
	}
}

func (re *requestExecutor) onNewBlockWithPause(block graphsync.BlockData) error {
	err := re.onNewBlock(block)
	select {
	case <-re.pauseMessages:
		re.sendRequest(gsmsg.CancelRequest(re.request.ID()))
		if err == nil {
			err = hooks.ErrPaused{}
		}
	default:
	}
	return err
}

func (re *requestExecutor) onNewBlock(block graphsync.BlockData) error {
	re.doNotSendCids.Add(block.Link().(cidlink.Link).Cid)
	return re.runBlockHooks(block)
}

func (re *requestExecutor) processResult(traverser ipldutil.Traverser, link ipld.Link, result types.AsyncLoadResult) error {
	if result.Err != nil {
		select {
		case <-re.ctx.Done():
			return ipldutil.ContextCancelError{}
		case re.inProgressErr <- result.Err:
			traverser.Error(traversal.SkipMe{})
			return nil
		}
	}
	err := re.onNewBlockWithPause(&blockData{link, result.Local, uint64(len(result.Data))})
	if err != nil {
		return err
	}
	err = traverser.Advance(bytes.NewReader(result.Data))
	if err != nil {
		return err
	}
	return nil
}

func (re *requestExecutor) sendRestartAsNeeded() error {
	if !re.restartNeeded {
		return nil
	}
	extensions := re.pendingExtensions
	re.pendingExtensions = nil
	re.restartNeeded = false
	cidsData, err := cidset.EncodeCidSet(re.doNotSendCids)
	if err != nil {
		return err
	}
	extensions = append(extensions, graphsync.ExtensionData{Name: graphsync.ExtensionDoNotSendCIDs, Data: cidsData})
	re.request = re.request.ReplaceExtensions(extensions)
	re.sendRequest(re.request)
	return nil
}

func isContextErr(err error) bool {
	// TODO: Match with errors.Is when https://github.com/ipld/go-ipld-prime/issues/58 is resolved
	return strings.Contains(err.Error(), ipldutil.ContextCancelError{}.Error())
}

type blockData struct {
	link  ipld.Link
	local bool
	size  uint64
}

// Link is the link/cid for the block
func (bd *blockData) Link() ipld.Link {
	return bd.link
}

// BlockSize specifies the size of the block
func (bd *blockData) BlockSize() uint64 {
	return bd.size
}

// BlockSize specifies the amount of data actually transmitted over the network
func (bd *blockData) BlockSizeOnWire() uint64 {
	if bd.local {
		return 0
	}
	return bd.size
}