traverser.go 5.84 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
Hannah Howard's avatar
Hannah Howard committed
28
	Chooser  traversal.LinkTargetNodeStyleChooser
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)
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
}

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)
60 61
func (tb TraversalBuilder) Start(parentCtx context.Context) Traverser {
	ctx, cancel := context.WithCancel(parentCtx)
62
	t := &traverser{
63
		parentCtx:    parentCtx,
64
		ctx:          ctx,
65
		cancel:       cancel,
66 67 68 69 70 71 72
		root:         tb.Root,
		selector:     tb.Selector,
		visitor:      defaultVisitor,
		chooser:      defaultChooser,
		awaitRequest: make(chan struct{}, 1),
		stateChan:    make(chan state, 1),
		responses:    make(chan nextResponse),
73
		stopped:      make(chan struct{}),
74 75 76 77 78 79 80 81 82 83 84 85 86 87
	}
	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 {
88
	parentCtx      context.Context
89
	ctx            context.Context
90
	cancel         func()
91 92 93
	root           ipld.Link
	selector       ipld.Node
	visitor        traversal.AdvVisitFn
Hannah Howard's avatar
Hannah Howard committed
94
	chooser        traversal.LinkTargetNodeStyleChooser
95 96 97 98 99 100 101
	currentLink    ipld.Link
	currentContext ipld.LinkContext
	isDone         bool
	completionErr  error
	awaitRequest   chan struct{}
	stateChan      chan state
	responses      chan nextResponse
102
	stopped        chan struct{}
103 104 105 106 107 108 109 110
}

func (t *traverser) checkState() {
	select {
	case <-t.awaitRequest:
		select {
		case <-t.ctx.Done():
			t.isDone = true
111
			t.completionErr = ContextCancelError{}
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
		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() {
136
		defer close(t.stopped)
137 138 139
		loader := func(lnk ipld.Link, lnkCtx ipld.LinkContext) (io.Reader, error) {
			select {
			case <-t.ctx.Done():
140
				return nil, ContextCancelError{}
141 142 143 144
			case t.stateChan <- state{false, nil, lnk, lnkCtx}:
			}
			select {
			case <-t.ctx.Done():
145
				return nil, ContextCancelError{}
146 147 148 149
			case response := <-t.responses:
				return response.input, response.err
			}
		}
Hannah Howard's avatar
Hannah Howard committed
150
		ns, err := t.chooser(t.root, ipld.LinkContext{})
151 152 153 154
		if err != nil {
			t.writeDone(err)
			return
		}
Hannah Howard's avatar
Hannah Howard committed
155 156
		nb := ns.NewBuilder()
		err = t.root.Load(t.ctx, ipld.LinkContext{}, nb, loader)
157 158 159 160
		if err != nil {
			t.writeDone(err)
			return
		}
Hannah Howard's avatar
Hannah Howard committed
161
		nd := nb.Build()
162 163 164 165 166 167 168 169

		sel, err := selector.ParseSelector(t.selector)
		if err != nil {
			t.writeDone(err)
			return
		}
		err = traversal.Progress{
			Cfg: &traversal.Config{
Hannah Howard's avatar
Hannah Howard committed
170 171 172
				Ctx:                        t.ctx,
				LinkLoader:                 loader,
				LinkTargetNodeStyleChooser: t.chooser,
173 174 175 176 177 178
			},
		}.WalkAdv(nd, sel, t.visitor)
		t.writeDone(err)
	}()
}

179 180 181 182 183 184 185 186
func (t *traverser) Shutdown(ctx context.Context) {
	t.cancel()
	select {
	case <-ctx.Done():
	case <-t.stopped:
	}
}

187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
// 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")
	}
	select {
	case <-t.ctx.Done():
208
		return ContextCancelError{}
209 210 211 212
	case t.awaitRequest <- struct{}{}:
	}
	select {
	case <-t.ctx.Done():
213
		return ContextCancelError{}
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
	case t.responses <- nextResponse{reader, nil}:
	}
	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}:
	}
}