-
Notifications
You must be signed in to change notification settings - Fork 44
/
selectivecar.go
289 lines (261 loc) · 7.5 KB
/
selectivecar.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 (
"bytes"
"context"
"errors"
"fmt"
"io"
"math"
cid "github.com/ipfs/go-cid"
util "github.com/ipld/go-car/util"
"github.com/ipld/go-ipld-prime"
cidlink "github.com/ipld/go-ipld-prime/linking/cid"
basicnode "github.com/ipld/go-ipld-prime/node/basic"
"github.com/ipld/go-ipld-prime/traversal"
"github.com/ipld/go-ipld-prime/traversal/selector"
// The dag-pb and raw codecs are necessary for unixfs.
dagpb "github.com/ipld/go-codec-dagpb"
_ "github.com/ipld/go-ipld-prime/codec/raw"
)
// Dag is a root/selector combo to put into a car
type Dag struct {
Root cid.Cid
Selector ipld.Node
}
// Block is all information and metadata about a block that is part of a car file
type Block struct {
BlockCID cid.Cid
Data []byte
Offset uint64
Size uint64
}
// SelectiveCar is a car file based on root + selector combos instead of just
// a single root and complete dag walk
type SelectiveCar struct {
ctx context.Context
dags []Dag
store ReadStore
opts options
}
// OnCarHeaderFunc is called during traversal when the header is created
type OnCarHeaderFunc func(CarHeader) error
// OnNewCarBlockFunc is called during traveral when a new unique block is encountered
type OnNewCarBlockFunc func(Block) error
// SelectiveCarPrepared is a SelectiveCar that has already been traversed, such that it
// can be written quicker with Dump. It also contains metadata already collection about
// the Car file like size and number of blocks that go into it
type SelectiveCarPrepared struct {
SelectiveCar
size uint64
header CarHeader
cids []cid.Cid
userOnNewCarBlocks []OnNewCarBlockFunc
}
// NewSelectiveCar creates a new SelectiveCar for the given car file based
// a block store and set of root+selector pairs
func NewSelectiveCar(ctx context.Context, store ReadStore, dags []Dag, opts ...Option) SelectiveCar {
return SelectiveCar{
ctx: ctx,
store: store,
dags: dags,
opts: applyOptions(opts...),
}
}
func (sc SelectiveCar) traverse(onCarHeader OnCarHeaderFunc, onNewCarBlock OnNewCarBlockFunc) (uint64, error) {
traverser := &selectiveCarTraverser{onCarHeader, onNewCarBlock, 0, cid.NewSet(), sc, cidlink.DefaultLinkSystem()}
traverser.lsys.StorageReadOpener = traverser.loader
return traverser.traverse()
}
// Prepare traverse a car file and collects data on what is about to be written, but
// does not actually write the file
func (sc SelectiveCar) Prepare(userOnNewCarBlocks ...OnNewCarBlockFunc) (SelectiveCarPrepared, error) {
var header CarHeader
var cids []cid.Cid
onCarHeader := func(h CarHeader) error {
header = h
return nil
}
onNewCarBlock := func(block Block) error {
cids = append(cids, block.BlockCID)
return nil
}
size, err := sc.traverse(onCarHeader, onNewCarBlock)
if err != nil {
return SelectiveCarPrepared{}, err
}
return SelectiveCarPrepared{sc, size, header, cids, userOnNewCarBlocks}, nil
}
func (sc SelectiveCar) Write(w io.Writer, userOnNewCarBlocks ...OnNewCarBlockFunc) error {
onCarHeader := func(h CarHeader) error {
if err := WriteHeader(&h, w); err != nil {
return fmt.Errorf("failed to write car header: %s", err)
}
return nil
}
onNewCarBlock := func(block Block) error {
err := util.LdWrite(w, block.BlockCID.Bytes(), block.Data)
if err != nil {
return err
}
for _, userOnNewCarBlock := range userOnNewCarBlocks {
err := userOnNewCarBlock(block)
if err != nil {
return err
}
}
return nil
}
_, err := sc.traverse(onCarHeader, onNewCarBlock)
return err
}
// Size returns the total size in bytes of the car file that will be written
func (sc SelectiveCarPrepared) Size() uint64 {
return sc.size
}
// Header returns the header for the car file that will be written
func (sc SelectiveCarPrepared) Header() CarHeader {
return sc.header
}
// Cids returns the list of unique block cids that will be written to the car file
func (sc SelectiveCarPrepared) Cids() []cid.Cid {
return sc.cids
}
// Dump writes the car file as quickly as possible based on information already
// collected
func (sc SelectiveCarPrepared) Dump(ctx context.Context, w io.Writer) error {
offset, err := HeaderSize(&sc.header)
if err != nil {
return fmt.Errorf("failed to size car header: %s", err)
}
if err := WriteHeader(&sc.header, w); err != nil {
return fmt.Errorf("failed to write car header: %s", err)
}
for _, c := range sc.cids {
blk, err := sc.store.Get(ctx, c)
if err != nil {
return err
}
raw := blk.RawData()
size := util.LdSize(c.Bytes(), raw)
err = util.LdWrite(w, c.Bytes(), raw)
if err != nil {
return err
}
for _, userOnNewCarBlock := range sc.userOnNewCarBlocks {
err := userOnNewCarBlock(Block{
BlockCID: c,
Data: raw,
Offset: offset,
Size: size,
})
if err != nil {
return err
}
}
offset += size
}
return nil
}
type selectiveCarTraverser struct {
onCarHeader OnCarHeaderFunc
onNewCarBlock OnNewCarBlockFunc
offset uint64
cidSet *cid.Set
sc SelectiveCar
lsys ipld.LinkSystem
}
func (sct *selectiveCarTraverser) traverse() (uint64, error) {
err := sct.traverseHeader()
if err != nil {
return 0, err
}
err = sct.traverseBlocks()
if err != nil {
return 0, err
}
return sct.offset, nil
}
func (sct *selectiveCarTraverser) traverseHeader() error {
roots := make([]cid.Cid, 0, len(sct.sc.dags))
for _, carDag := range sct.sc.dags {
roots = append(roots, carDag.Root)
}
header := CarHeader{
Roots: roots,
Version: 1,
}
size, err := HeaderSize(&header)
if err != nil {
return err
}
sct.offset += size
return sct.onCarHeader(header)
}
func (sct *selectiveCarTraverser) loader(ctx ipld.LinkContext, lnk ipld.Link) (io.Reader, error) {
cl, ok := lnk.(cidlink.Link)
if !ok {
return nil, errors.New("incorrect link type")
}
c := cl.Cid
blk, err := sct.sc.store.Get(ctx.Ctx, c)
if err != nil {
return nil, err
}
raw := blk.RawData()
if !sct.cidSet.Has(c) {
sct.cidSet.Add(c)
size := util.LdSize(c.Bytes(), raw)
err := sct.onNewCarBlock(Block{
BlockCID: c,
Data: raw,
Offset: sct.offset,
Size: size,
})
if err != nil {
return nil, err
}
sct.offset += size
}
return bytes.NewReader(raw), nil
}
func (sct *selectiveCarTraverser) traverseBlocks() error {
nsc := func(lnk ipld.Link, lctx ipld.LinkContext) (ipld.NodePrototype, error) {
// We can decode all nodes into basicnode's Any, except for
// dagpb nodes, which must explicitly use the PBNode prototype.
if lnk, ok := lnk.(cidlink.Link); ok && lnk.Cid.Prefix().Codec == 0x70 {
return dagpb.Type.PBNode, nil
}
return basicnode.Prototype.Any, nil
}
for _, carDag := range sct.sc.dags {
parsed, err := selector.ParseSelector(carDag.Selector)
if err != nil {
return err
}
lnk := cidlink.Link{Cid: carDag.Root}
ns, _ := nsc(lnk, ipld.LinkContext{}) // nsc won't error
nd, err := sct.lsys.Load(ipld.LinkContext{Ctx: sct.sc.ctx}, lnk, ns)
if err != nil {
return err
}
prog := traversal.Progress{
Cfg: &traversal.Config{
Ctx: sct.sc.ctx,
LinkSystem: sct.lsys,
LinkTargetNodePrototypeChooser: nsc,
LinkVisitOnlyOnce: sct.sc.opts.TraverseLinksOnlyOnce,
},
}
if sct.sc.opts.MaxTraversalLinks < math.MaxInt64 {
prog.Budget = &traversal.Budget{
NodeBudget: math.MaxInt64,
LinkBudget: int64(sct.sc.opts.MaxTraversalLinks),
}
}
err = prog.WalkAdv(nd, parsed, func(traversal.Progress, ipld.Node, traversal.VisitReason) error { return nil })
if err != nil {
return err
}
}
return nil
}