traverser.go 6.08 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
package ipldutil

import (
	"context"
	"errors"
	"io"

	"github.com/ipld/go-ipld-prime"
	"github.com/ipld/go-ipld-prime/traversal"
	"github.com/ipld/go-ipld-prime/traversal/selector"
)

var defaultVisitor traversal.AdvVisitFn = func(traversal.Progress, ipld.Node, traversal.VisitReason) error { return nil }

15 16 17 18 19 20 21 22
// ContextCancelError is a sentinel that indicates the passed in context
// was cancelled
type ContextCancelError struct{}

func (cp ContextCancelError) Error() string {
	return "Context cancelled"
}

23 24 25 26 27
// TraversalBuilder defines parameters for an iterative traversal
type TraversalBuilder struct {
	Root     ipld.Link
	Selector ipld.Node
	Visitor  traversal.AdvVisitFn
Eric Myhre's avatar
Eric Myhre committed
28
	Chooser  traversal.LinkTargetNodePrototypeChooser
29 30 31 32 33 34 35 36 37 38 39 40 41
}

// Traverser is an interface for performing a selector traversal that operates iteratively --
// it stops and waits for a manual load every time a block boundary is encountered
type Traverser interface {
	// IsComplete returns the completion state (boolean) and if so, the final error result from IPLD
	IsComplete() (bool, error)
	// Current request returns the current link waiting to be loaded
	CurrentRequest() (ipld.Link, ipld.LinkContext)
	// Advance advances the traversal successfully by supplying the given reader as the result of the next IPLD load
	Advance(reader io.Reader) error
	// Error errors the traversal by returning the given error as the result of the next IPLD load
	Error(err error)
42 43
	// Shutdown cancels the traversal
	Shutdown(ctx context.Context)
Aarsh Shah's avatar
Aarsh Shah committed
44 45
	// NBlocksTraversed returns the number of blocks successfully traversed
	NBlocksTraversed() int
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
}

type state struct {
	isDone         bool
	completionErr  error
	currentLink    ipld.Link
	currentContext ipld.LinkContext
}

type nextResponse struct {
	input io.Reader
	err   error
}

// Start initiates the traversal (run in a go routine because the regular
// selector traversal expects a call back)
62 63
func (tb TraversalBuilder) Start(parentCtx context.Context) Traverser {
	ctx, cancel := context.WithCancel(parentCtx)
64
	t := &traverser{
Aarsh Shah's avatar
Aarsh Shah committed
65
		blocksCount:  0,
66
		parentCtx:    parentCtx,
67
		ctx:          ctx,
68
		cancel:       cancel,
69 70 71 72 73 74 75
		root:         tb.Root,
		selector:     tb.Selector,
		visitor:      defaultVisitor,
		chooser:      defaultChooser,
		awaitRequest: make(chan struct{}, 1),
		stateChan:    make(chan state, 1),
		responses:    make(chan nextResponse),
76
		stopped:      make(chan struct{}),
77 78 79 80 81 82 83 84 85 86 87 88 89 90
	}
	if tb.Visitor != nil {
		t.visitor = tb.Visitor
	}
	if tb.Chooser != nil {
		t.chooser = tb.Chooser
	}
	t.start()
	return t
}

// traverser is a class to perform a selector traversal that stops every time a new block is loaded
// and waits for manual input (in the form of advance or error)
type traverser struct {
Aarsh Shah's avatar
Aarsh Shah committed
91
	blocksCount    int
92
	parentCtx      context.Context
93
	ctx            context.Context
94
	cancel         func()
95 96 97
	root           ipld.Link
	selector       ipld.Node
	visitor        traversal.AdvVisitFn
Eric Myhre's avatar
Eric Myhre committed
98
	chooser        traversal.LinkTargetNodePrototypeChooser
99 100 101 102 103 104 105
	currentLink    ipld.Link
	currentContext ipld.LinkContext
	isDone         bool
	completionErr  error
	awaitRequest   chan struct{}
	stateChan      chan state
	responses      chan nextResponse
106
	stopped        chan struct{}
107 108
}

Aarsh Shah's avatar
Aarsh Shah committed
109 110 111 112
func (t *traverser) NBlocksTraversed() int {
	return t.blocksCount
}

113 114 115 116 117 118
func (t *traverser) checkState() {
	select {
	case <-t.awaitRequest:
		select {
		case <-t.ctx.Done():
			t.isDone = true
119
			t.completionErr = ContextCancelError{}
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
		case newState := <-t.stateChan:
			t.isDone = newState.isDone
			t.completionErr = newState.completionErr
			t.currentLink = newState.currentLink
			t.currentContext = newState.currentContext
		}
	default:
	}
}

func (t *traverser) writeDone(err error) {
	select {
	case <-t.ctx.Done():
	case t.stateChan <- state{true, err, nil, ipld.LinkContext{}}:
	}
}

func (t *traverser) start() {
	select {
	case <-t.ctx.Done():
		return
	case t.awaitRequest <- struct{}{}:
	}
	go func() {
144
		defer close(t.stopped)
145 146 147
		loader := func(lnk ipld.Link, lnkCtx ipld.LinkContext) (io.Reader, error) {
			select {
			case <-t.ctx.Done():
148
				return nil, ContextCancelError{}
149 150 151 152
			case t.stateChan <- state{false, nil, lnk, lnkCtx}:
			}
			select {
			case <-t.ctx.Done():
153
				return nil, ContextCancelError{}
154 155 156 157
			case response := <-t.responses:
				return response.input, response.err
			}
		}
Hannah Howard's avatar
Hannah Howard committed
158
		ns, err := t.chooser(t.root, ipld.LinkContext{})
159 160 161 162
		if err != nil {
			t.writeDone(err)
			return
		}
Hannah Howard's avatar
Hannah Howard committed
163 164
		nb := ns.NewBuilder()
		err = t.root.Load(t.ctx, ipld.LinkContext{}, nb, loader)
165 166 167 168
		if err != nil {
			t.writeDone(err)
			return
		}
Hannah Howard's avatar
Hannah Howard committed
169
		nd := nb.Build()
170 171 172 173 174 175 176 177

		sel, err := selector.ParseSelector(t.selector)
		if err != nil {
			t.writeDone(err)
			return
		}
		err = traversal.Progress{
			Cfg: &traversal.Config{
hannahhoward's avatar
hannahhoward committed
178 179
				Ctx:                            t.ctx,
				LinkLoader:                     loader,
Eric Myhre's avatar
Eric Myhre committed
180
				LinkTargetNodePrototypeChooser: t.chooser,
181 182 183 184 185 186
			},
		}.WalkAdv(nd, sel, t.visitor)
		t.writeDone(err)
	}()
}

187 188 189 190 191 192 193 194
func (t *traverser) Shutdown(ctx context.Context) {
	t.cancel()
	select {
	case <-ctx.Done():
	case <-t.stopped:
	}
}

195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
// IsComplete returns true if a traversal is complete
func (t *traverser) IsComplete() (bool, error) {
	t.checkState()
	return t.isDone, t.completionErr
}

// CurrentRequest returns the current block load waiting to be fulfilled in order
// to advance further
func (t *traverser) CurrentRequest() (ipld.Link, ipld.LinkContext) {
	t.checkState()
	return t.currentLink, t.currentContext
}

// Advance advances the traversal with an io.Reader for the next requested block
func (t *traverser) Advance(reader io.Reader) error {
	isComplete, _ := t.IsComplete()
	if isComplete {
		return errors.New("cannot advance when done")
	}
Aarsh Shah's avatar
Aarsh Shah committed
214

215 216
	select {
	case <-t.ctx.Done():
217
		return ContextCancelError{}
218 219
	case t.awaitRequest <- struct{}{}:
	}
Aarsh Shah's avatar
Aarsh Shah committed
220

221 222
	select {
	case <-t.ctx.Done():
223
		return ContextCancelError{}
224 225
	case t.responses <- nextResponse{reader, nil}:
	}
Aarsh Shah's avatar
Aarsh Shah committed
226 227

	t.blocksCount++
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
	return nil
}

// Error aborts the traversal with an error
func (t *traverser) Error(err error) {
	isComplete, _ := t.IsComplete()
	if isComplete {
		return
	}
	select {
	case <-t.ctx.Done():
		return
	case t.awaitRequest <- struct{}{}:
	}
	select {
	case <-t.ctx.Done():
	case t.responses <- nextResponse{nil, err}:
	}
}