1 package lattice
2 3 import (
4 "fmt"
5 "os"
6 "sort"
7 )
8 9 // DB is an .iskr tree with its .meta and .tokpool companions, the pair
10 // iskra/storage.mx StorageOpen, StorageFlush and StorageClose manage.
11 //
12 // TokenPool keeps the token pool in memory: the Go writer does not implement
13 // the append-only .tokpool file, so a base path with tokens held in .tokpool is
14 // refused rather than silently written back without them. A base path whose
15 // .tokpool is absent or empty is fully representable and round-trips.
16 type DB struct {
17 BasePath string
18 Tree *Tree
19 Meta *MetaFile
20 TokCount uint32 // token entries in the .tokpool file, 0 when none
21 HasTokFile bool
22 }
23 24 // OpenISKR opens base+".iskr" and, if it exists, base+".meta". A .tokpool that
25 // is non-empty is an error: see DB.
26 func OpenISKR(base string) (*DB, error) {
27 t, err := OpenStoreTree(base + ".iskr")
28 if err != nil {
29 return nil, err
30 }
31 db := &DB{BasePath: base, Tree: t}
32 metaPath := base + ".meta"
33 if _, statErr := os.Stat(metaPath); statErr == nil {
34 m, e := DecodeMetaFile(metaPath)
35 if e != nil {
36 t.Close()
37 return nil, fmt.Errorf("lattice: %s: %w", metaPath, e)
38 }
39 db.Meta = m
40 if uint32(len(m.Records)) != t.RecordCount() {
41 t.Close()
42 return nil, fmt.Errorf("lattice: %s has %d meta records but %s has %d records",
43 metaPath, len(m.Records), base+".iskr", t.RecordCount())
44 }
45 }
46 tokPath := base + ".tokpool"
47 if st, statErr := os.Stat(tokPath); statErr == nil {
48 db.HasTokFile = true
49 db.TokCount = uint32(st.Size() / 4)
50 if db.TokCount > 0 {
51 t.Close()
52 return nil, fmt.Errorf("lattice: %s holds %d token entries; the Go writer does not yet write .tokpool, so this base path is read-refused rather than written back incomplete", tokPath, db.TokCount)
53 }
54 }
55 return db, nil
56 }
57 58 // Flush writes .meta atomically, then flushes the .iskr. The order is the
59 // moxie one: a crash between the two leaves a .meta that the previous valid
60 // .iskr can be re-derived from, never a .iskr no .meta describes.
61 func (db *DB) Flush() error {
62 if db.Meta != nil {
63 if uint32(len(db.Meta.Records)) != db.Tree.RecordCount() {
64 return fmt.Errorf("lattice: refusing to flush: .meta has %d records, tree has %d",
65 len(db.Meta.Records), db.Tree.RecordCount())
66 }
67 if err := EncodeMeta(db.BasePath+".meta", db.Meta, len(db.Meta.TokenPool) > 0); err != nil {
68 return err
69 }
70 }
71 return db.Tree.Flush()
72 }
73 74 // Close flushes then closes the tree.
75 func (db *DB) Close() error {
76 if err := db.Flush(); err != nil {
77 return err
78 }
79 return db.Tree.Close()
80 }
81 82 // KeyVisitor is called for every key a Query reaches, in ascending key order
83 // within a branch. Return false to stop that branch early.
84 type KeyVisitor func(branch Branch, key Key, recIdx uint32, rec Record) bool
85 86 // Query walks every block a root chain reaches, in key order within each
87 // branch, and visits each key slot that names a record. This is what a lattice
88 // query sees: the keys in files placed by whichever writer produced them are
89 // only part of what the file holds when the writer detached blocks, so the
90 // header distinguishes keys in blocks a root reaches (Queries) from keys held
91 // only behind a record pointer (PlantKeys).
92 //
93 // A block whose key count exceeds C is read as C keys and C+1 children.
94 func (t *Tree) Query(v KeyVisitor) error {
95 for b := 0; b < C; b++ {
96 if err := t.queryBranch(Branch(b), v); err != nil {
97 return err
98 }
99 }
100 return nil
101 }
102 103 func (t *Tree) queryBranch(branch Branch, v KeyVisitor) error {
104 var walk func(idx uint32, depth int) error
105 walk = func(idx uint32, depth int) error {
106 if depth >= MaxTreeDepth {
107 return errCycle("Query", branch)
108 }
109 n, err := t.GetNode(idx)
110 if err != nil {
111 return err
112 }
113 k := n.Count()
114 leaf := n.Children[0] == NullIndex
115 for i := 0; i < k; i++ {
116 if !leaf {
117 if err := walk(n.Children[i], depth+1); err != nil {
118 return err
119 }
120 }
121 ri := n.RecPtrs[i]
122 if ri == NullRec || ri >= t.rCount {
123 continue
124 }
125 rec, err := t.GetRecord(ri)
126 if err != nil {
127 return err
128 }
129 if !v(branch, n.Keys[i], ri, *rec) {
130 return nil
131 }
132 }
133 if !leaf {
134 return walk(n.Children[k], depth+1)
135 }
136 return nil
137 }
138 return walk(t.Roots[branch], 0)
139 }
140 141 // PlantedQuery walks every key slot in every block, root chain or not, in
142 // block index order, so a caller can check that all of them come back through
143 // PlantedLookup.
144 func (t *Tree) PlantedQuery(v KeyVisitor) error {
145 for i := uint32(0); i < t.nCount; i++ {
146 n, err := t.GetNode(i)
147 if err != nil {
148 return err
149 }
150 k := n.Count()
151 for j := 0; j < k; j++ {
152 ri := n.RecPtrs[j]
153 if ri == NullRec || ri >= t.rCount {
154 continue
155 }
156 rec, err := t.GetRecord(ri)
157 if err != nil {
158 return err
159 }
160 if !v(Branch(rec.Branch), n.Keys[j], ri, *rec) {
161 return nil
162 }
163 }
164 }
165 return nil
166 }
167 168 // PlantedLookup finds a key by scanning every block of one branch, in block
169 // order: the same result a Query of the whole branch gives for a key that sits
170 // behind a record pointer, without trusting a separate index to say so.
171 func (t *Tree) PlantedLookup(branch Branch, key Key) (recIdx uint32, rec *Record, err error) {
172 for i := uint32(0); i < t.nCount; i++ {
173 n, err := t.GetNode(i)
174 if err != nil {
175 return NullRec, nil, err
176 }
177 if n.GetBranch() != branch {
178 continue
179 }
180 k := n.Count()
181 for j := 0; j < k; j++ {
182 if n.Keys[j] != key {
183 continue
184 }
185 ri := n.RecPtrs[j]
186 if ri == NullRec || ri >= t.rCount {
187 return NullRec, nil, fmt.Errorf("lattice: block %d slot %d holds a null record pointer for key %#x", i, j, key)
188 }
189 r, err := t.GetRecord(ri)
190 return ri, r, err
191 }
192 }
193 return NullRec, nil, nil
194 }
195 196 // SampleKeys returns up to n reached (branch, key) pairs spread evenly over the
197 // Query order, for a spot check that looks each one up again.
198 func SampleKeys(t *Tree, n int) ([][2]uint64, error) {
199 var all [][2]uint64
200 err := t.Query(func(branch Branch, key Key, recIdx uint32, rec Record) bool {
201 all = append(all, [2]uint64{uint64(branch), uint64(key)})
202 return true
203 })
204 if err != nil || len(all) == 0 {
205 return nil, err
206 }
207 if n > len(all) {
208 n = len(all)
209 }
210 out := make([][2]uint64, 0, n)
211 step := len(all) / n
212 if step < 1 {
213 step = 1
214 }
215 for i := 0; len(out) < n && i < len(all); i += step {
216 out = append(out, all[i])
217 }
218 return out, nil
219 }
220 221 // CopyToMemory reproduces t as a fresh in-memory tree with the same roots,
222 // free list, blocks at the same indices, Mult and Flags, and record pointers
223 // renumbered densely from 1 in record order. The returned map takes old record
224 // indices to new.
225 //
226 // The renumbering exists for the MESH format, whose record index 0 is its null
227 // pointer. It is wrong for a .iskr round trip: an .iskr stores record 0
228 // (iskra/storage.mx bound the old null test as recIdx >= rCount, which is always
229 // false), and CopyToMemoryV5 does not renumber. Use CopyToMemoryV5 to write an
230 // .iskr back.
231 func (t *Tree) CopyToMemory() (*Tree, map[uint32]uint32, error) {
232 dst := AllocTree(t.nCount, t.rCount+1, t.Roots)
233 remap := make(map[uint32]uint32, t.rCount)
234 for i := uint32(0); i < t.rCount; i++ {
235 remap[i] = i + 1
236 }
237 dst.rCount = t.rCount + 1
238 dst.FreeHead = t.FreeHead
239 dst.FreeCount = t.FreeCount
240 dst.Pending = append([]PendingExp(nil), t.Pending...)
241 for i := uint32(0); i < t.nCount; i++ {
242 n, err := t.GetNode(i)
243 if err != nil {
244 return nil, nil, err
245 }
246 c := *n
247 for j := 0; j < C; j++ {
248 if c.RecPtrs[j] == NullRec {
249 continue
250 }
251 if c.RecPtrs[j] >= t.rCount {
252 return nil, nil, fmt.Errorf("lattice: block %d slot %d holds record pointer %d beyond %d records", i, j, c.RecPtrs[j], t.rCount)
253 }
254 c.RecPtrs[j]++
255 }
256 dst.Nodes[i] = c
257 }
258 for i := uint32(0); i < t.rCount; i++ {
259 r, err := t.GetRecord(i)
260 if err != nil {
261 return nil, nil, err
262 }
263 c := *r
264 for li := 0; li < 2; li++ {
265 if c.Link[li] == NullRec || c.Link[li] == 0 {
266 c.Link[li] = NullRec
267 continue
268 }
269 if c.Link[li] >= t.rCount {
270 return nil, nil, fmt.Errorf("lattice: record %d link %d points at %d beyond %d records", i, li, c.Link[li], t.rCount)
271 }
272 c.Link[li]++
273 }
274 dst.Records[i+1] = c
275 }
276 dst.Records[0].Link = [2]uint32{NullRec, NullRec}
277 dst.Meta = append([]MetaEntry(nil), t.Meta...)
278 dst.Lex = append([]LexEntry(nil), t.Lex...)
279 dst.Adj = append([]AdjLink(nil), t.Adj...)
280 dst.StringPool = append([]byte(nil), t.StringPool...)
281 dst.rebuildRecKey()
282 return dst, remap, nil
283 }
284 285 // CopyToMemoryV5 copies every block and record of t into a fresh in-memory
286 // tree exactly: same block indices, same record indices, the same 48 bytes per
287 // record, the same roots, free list and journal. Nothing is renumbered, so a
288 // tree written back from this copy has the same header it was read from.
289 //
290 // It copies every block, including blocks no root reaches, because a round trip
291 // that dropped those would change the file it claims to preserve.
292 func (t *Tree) CopyToMemoryV5() (*Tree, error) {
293 dst := AllocTree(t.nCount, t.rCount, t.Roots)
294 dst.rCount = t.rCount
295 dst.FreeHead = t.FreeHead
296 dst.FreeCount = t.FreeCount
297 dst.Pending = append([]PendingExp(nil), t.Pending...)
298 for i := uint32(0); i < t.nCount; i++ {
299 n, err := t.GetNode(i)
300 if err != nil {
301 return nil, err
302 }
303 dst.Nodes[i] = *n
304 }
305 for i := uint32(0); i < t.rCount; i++ {
306 r, err := t.GetRecord(i)
307 if err != nil {
308 return nil, err
309 }
310 dst.Records[i] = *r
311 }
312 dst.Meta = append([]MetaEntry(nil), t.Meta...)
313 dst.Lex = append([]LexEntry(nil), t.Lex...)
314 dst.Adj = append([]AdjLink(nil), t.Adj...)
315 dst.StringPool = append([]byte(nil), t.StringPool...)
316 dst.SourceVersion = Version
317 dst.rebuildRecKey()
318 return dst, nil
319 }
320 321 // SameAs reports the first difference between two trees, or nil when every
322 // block (index, keys, record pointers, children, Mult, Flags), every record and
323 // the roots, free list and journal are identical.
324 func (t *Tree) SameAs(o *Tree) error {
325 if t.nCount != o.nCount || t.rCount != o.rCount {
326 return fmt.Errorf("block count %d/%d or record count %d/%d differs", t.nCount, o.nCount, t.rCount, o.rCount)
327 }
328 if t.Roots != o.Roots || t.FreeHead != o.FreeHead || t.FreeCount != o.FreeCount {
329 return fmt.Errorf("roots, free head or free count differ")
330 }
331 if len(t.Pending) != len(o.Pending) {
332 return fmt.Errorf("journal lengths differ")
333 }
334 for i := range t.Pending {
335 if t.Pending[i] != o.Pending[i] {
336 return fmt.Errorf("journal entry %d differs", i)
337 }
338 }
339 for i := uint32(0); i < t.nCount; i++ {
340 a, err := t.GetNode(i)
341 if err != nil {
342 return err
343 }
344 b, err := o.GetNode(i)
345 if err != nil {
346 return err
347 }
348 if *a != *b {
349 return fmt.Errorf("block %d differs", i)
350 }
351 }
352 for i := uint32(0); i < t.rCount; i++ {
353 a, err := t.GetRecord(i)
354 if err != nil {
355 return err
356 }
357 b, err := o.GetRecord(i)
358 if err != nil {
359 return err
360 }
361 if *a != *b {
362 return fmt.Errorf("record %d differs", i)
363 }
364 }
365 return nil
366 }
367 368 // QueryDigest is a single number standing for the whole reachable key set,
369 // record contents included, in Query order.
370 func (t *Tree) QueryDigest() (uint64, int, error) {
371 h := fnvOffset64
372 n := 0
373 buf := make([]byte, RecordSize)
374 err := t.Query(func(branch Branch, key Key, recIdx uint32, rec Record) bool {
375 encodeRecord(&rec, buf)
376 h = fnv1(h, []byte{byte(branch)})
377 h = fnv1(h, le64(uint64(key)))
378 h = fnv1(h, le64(uint64(recIdx)))
379 h = fnv1(h, buf)
380 n++
381 return true
382 })
383 return h, n, err
384 }
385 386 // WriteISKRMemory writes an in-memory tree as base+".iskr" and, when meta is
387 // non-nil, base+".meta", placing every key and record exactly where the tree
388 // holds them. This is the writer gate 3 writes through.
389 func WriteISKRMemory(base string, t *Tree, meta *MetaFile) error {
390 if !t.IsMemory() {
391 return fmt.Errorf("lattice: WriteISKRMemory needs an in-memory tree")
392 }
393 if meta != nil && uint32(len(meta.Records)) != t.rCount {
394 return fmt.Errorf("lattice: .meta has %d records, tree has %d", len(meta.Records), t.rCount)
395 }
396 if err := SaveFile(base+".iskr", t); err != nil {
397 return err
398 }
399 if meta != nil {
400 if err := EncodeMeta(base+".meta", meta, len(meta.TokenPool) > 0); err != nil {
401 return err
402 }
403 }
404 return nil
405 }
406 407 // ReadISKRMemory reads base+".iskr" and base+".meta" into an in-memory tree,
408 // placing every key and record exactly where the file holds them. It exists so
409 // a .iskr can be read, written and re-read without the MESH format, which
410 // needs a key index the .iskr does not store.
411 func ReadISKRMemory(base string) (*Tree, *MetaFile, error) {
412 t, err := LoadFile(base + ".iskr")
413 if err != nil {
414 return nil, nil, err
415 }
416 metaPath := base + ".meta"
417 if _, statErr := os.Stat(metaPath); statErr == nil {
418 m, e := DecodeMetaFile(metaPath)
419 if e != nil {
420 return nil, nil, e
421 }
422 if uint32(len(m.Records)) != t.rCount {
423 return nil, nil, fmt.Errorf("lattice: %s has %d records, %s has %d", metaPath, len(m.Records), base+".iskr", t.rCount)
424 }
425 return t, m, nil
426 }
427 return t, nil, nil
428 }
429 430 // sortedBranchKeys returns every reached (branch,key) pair, ascending.
431 func sortedBranchKeys(t *Tree) ([][2]uint64, error) {
432 var out [][2]uint64
433 err := t.Query(func(branch Branch, key Key, recIdx uint32, rec Record) bool {
434 out = append(out, [2]uint64{uint64(branch), uint64(key)})
435 return true
436 })
437 sort.Slice(out, func(i, j int) bool {
438 if out[i][0] != out[j][0] {
439 return out[i][0] < out[j][0]
440 }
441 return out[i][1] < out[j][1]
442 })
443 return out, err
444 }
445 446 func max(a, b int) int {
447 if a > b {
448 return a
449 }
450 return b
451 }
452 453 // FileSizeOnDisk is the size of the tree's file, or 0 for an in-memory tree.
454 func (t *Tree) FileSizeOnDisk() (int64, error) {
455 if t.Store == nil {
456 return 0, nil
457 }
458 st, err := t.Store.File().Stat()
459 if err != nil {
460 return 0, err
461 }
462 return st.Size(), nil
463 }
464