-
Notifications
You must be signed in to change notification settings - Fork 44
/
selective.go
289 lines (256 loc) · 7.19 KB
/
selective.go
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
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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
package car
import (
"context"
"fmt"
"io"
"math"
"os"
"github.com/ipfs/go-cid"
"github.com/ipld/go-car/v2/index"
"github.com/ipld/go-car/v2/internal/carv1"
"github.com/ipld/go-car/v2/internal/loader"
ipld "github.com/ipld/go-ipld-prime"
"github.com/ipld/go-ipld-prime/datamodel"
"github.com/ipld/go-ipld-prime/linking"
cidlink "github.com/ipld/go-ipld-prime/linking/cid"
"github.com/ipld/go-ipld-prime/node/basicnode"
"github.com/ipld/go-ipld-prime/traversal"
"github.com/ipld/go-ipld-prime/traversal/selector"
)
// ErrSizeMismatch is returned when a written traversal realizes the written header size does not
// match the actual number of car bytes written.
var ErrSizeMismatch = fmt.Errorf("car-error-sizemismatch")
// ErrOffsetImpossible is returned when specified paddings or offsets of either a wrapped carv1
// or index cannot be satisfied based on the data being written.
var ErrOffsetImpossible = fmt.Errorf("car-error-offsetimpossible")
// MaxTraversalLinks changes the allowed number of links a selector traversal
// can execute before failing.
//
// Note that setting this option may cause an error to be returned from selector
// execution when building a SelectiveCar.
func MaxTraversalLinks(MaxTraversalLinks uint64) Option {
return func(sco *Options) {
sco.MaxTraversalLinks = MaxTraversalLinks
}
}
// NewSelectiveWriter walks through the proposed dag traversal to learn its total size in order to be able to
// stream out a car to a writer in the expected traversal order in one go.
func NewSelectiveWriter(ctx context.Context, ls *ipld.LinkSystem, root cid.Cid, selector ipld.Node, opts ...Option) (Writer, error) {
cls, cntr := loader.CountingLinkSystem(*ls)
c1h := carv1.CarHeader{Roots: []cid.Cid{root}, Version: 1}
headSize, err := carv1.HeaderSize(&c1h)
if err != nil {
return nil, err
}
if err := traverse(ctx, &cls, root, selector, ApplyOptions(opts...)); err != nil {
return nil, err
}
tc := traversalCar{
size: headSize + cntr.Size(),
ctx: ctx,
root: root,
selector: selector,
ls: ls,
opts: ApplyOptions(opts...),
}
return &tc, nil
}
// TraverseToFile writes a car file matching a given root and selector to the
// path at `destination` using one read of each block.
func TraverseToFile(ctx context.Context, ls *ipld.LinkSystem, root cid.Cid, selector ipld.Node, destination string, opts ...Option) error {
tc := traversalCar{
size: 0,
ctx: ctx,
root: root,
selector: selector,
ls: ls,
opts: ApplyOptions(opts...),
}
fp, err := os.Create(destination)
if err != nil {
return err
}
defer fp.Close()
_, err = tc.WriteTo(fp)
if err != nil {
return err
}
// fix header size.
if _, err = fp.Seek(0, 0); err != nil {
return err
}
tc.size = uint64(tc.size)
if _, err = tc.WriteV2Header(fp); err != nil {
return err
}
return nil
}
// TraverseV1 walks through the proposed dag traversal and writes a carv1 to the provided io.Writer
func TraverseV1(ctx context.Context, ls *ipld.LinkSystem, root cid.Cid, selector ipld.Node, writer io.Writer, opts ...Option) (uint64, error) {
opts = append(opts, WithoutIndex())
tc := traversalCar{
size: 0,
ctx: ctx,
root: root,
selector: selector,
ls: ls,
opts: ApplyOptions(opts...),
}
len, _, err := tc.WriteV1(writer)
return len, err
}
// Writer is an interface allowing writing a car prepared by PrepareTraversal
type Writer interface {
io.WriterTo
}
var _ Writer = (*traversalCar)(nil)
type traversalCar struct {
size uint64
ctx context.Context
root cid.Cid
selector ipld.Node
ls *ipld.LinkSystem
opts Options
}
func (tc *traversalCar) WriteTo(w io.Writer) (int64, error) {
n, err := tc.WriteV2Header(w)
if err != nil {
return n, err
}
v1s, idx, err := tc.WriteV1(w)
n += int64(v1s)
if err != nil {
return n, err
}
// index padding, then index
if tc.opts.IndexCodec != index.CarIndexNone {
if tc.opts.IndexPadding > 0 {
buf := make([]byte, tc.opts.IndexPadding)
pn, err := w.Write(buf)
n += int64(pn)
if err != nil {
return n, err
}
}
in, err := index.WriteTo(idx, w)
n += int64(in)
if err != nil {
return n, err
}
}
return n, err
}
func (tc *traversalCar) WriteV2Header(w io.Writer) (int64, error) {
n, err := w.Write(Pragma)
if err != nil {
return int64(n), err
}
h := NewHeader(tc.size)
if p := tc.opts.DataPadding; p > 0 {
h = h.WithDataPadding(p)
}
if p := tc.opts.IndexPadding; p > 0 {
h = h.WithIndexPadding(p)
}
if tc.opts.IndexCodec == index.CarIndexNone {
h.IndexOffset = 0
}
hn, err := h.WriteTo(w)
if err != nil {
return int64(n) + hn, err
}
hn += int64(n)
// We include the initial data padding after the carv2 header
if h.DataOffset > uint64(hn) {
// TODO: buffer writes if this needs to be big.
buf := make([]byte, h.DataOffset-uint64(hn))
n, err = w.Write(buf)
hn += int64(n)
if err != nil {
return hn, err
}
} else if h.DataOffset < uint64(hn) {
return hn, ErrOffsetImpossible
}
return hn, nil
}
func (tc *traversalCar) WriteV1(w io.Writer) (uint64, index.Index, error) {
// write the v1 header
c1h := carv1.CarHeader{Roots: []cid.Cid{tc.root}, Version: 1}
if err := carv1.WriteHeader(&c1h, w); err != nil {
return 0, nil, err
}
v1Size, err := carv1.HeaderSize(&c1h)
if err != nil {
return v1Size, nil, err
}
// write the block.
wls, writer := loader.TeeingLinkSystem(*tc.ls, w, v1Size, tc.opts.IndexCodec)
err = traverse(tc.ctx, &wls, tc.root, tc.selector, tc.opts)
v1Size = writer.Size()
if err != nil {
return v1Size, nil, err
}
if tc.size != 0 && tc.size != v1Size {
return v1Size, nil, ErrSizeMismatch
}
tc.size = v1Size
if tc.opts.IndexCodec == index.CarIndexNone {
return v1Size, nil, nil
}
idx, err := writer.Index()
return v1Size, idx, err
}
func traverse(ctx context.Context, ls *ipld.LinkSystem, root cid.Cid, s ipld.Node, opts Options) error {
sel, err := selector.CompileSelector(s)
if err != nil {
return err
}
chooser := func(_ ipld.Link, _ linking.LinkContext) (ipld.NodePrototype, error) {
return basicnode.Prototype.Any, nil
}
if opts.TraversalPrototypeChooser != nil {
chooser = opts.TraversalPrototypeChooser
}
progress := traversal.Progress{
Cfg: &traversal.Config{
Ctx: ctx,
LinkSystem: *ls,
LinkTargetNodePrototypeChooser: chooser,
LinkVisitOnlyOnce: !opts.BlockstoreAllowDuplicatePuts,
},
}
if opts.MaxTraversalLinks < math.MaxInt64 {
progress.Budget = &traversal.Budget{
NodeBudget: math.MaxInt64,
LinkBudget: int64(opts.MaxTraversalLinks),
}
}
lnk := cidlink.Link{Cid: root}
ls.TrustedStorage = true
rp, err := chooser(lnk, ipld.LinkContext{})
if err != nil {
return err
}
rootNode, err := ls.Load(ipld.LinkContext{}, lnk, rp)
if err != nil {
return fmt.Errorf("root blk load failed: %s", err)
}
err = progress.WalkMatching(rootNode, sel, func(_ traversal.Progress, node ipld.Node) error {
if lbn, ok := node.(datamodel.LargeBytesNode); ok {
s, err := lbn.AsLargeBytes()
if err != nil {
return err
}
_, err = io.Copy(io.Discard, s)
if err != nil {
return err
}
}
return nil
})
if err != nil {
return fmt.Errorf("walk failed: %s", err)
}
return nil
}