package lattice import ( "fmt" "os" "sort" ) // DB is an .iskr tree with its .meta and .tokpool companions, the pair // iskra/storage.mx StorageOpen, StorageFlush and StorageClose manage. // // TokenPool keeps the token pool in memory: the Go writer does not implement // the append-only .tokpool file, so a base path with tokens held in .tokpool is // refused rather than silently written back without them. A base path whose // .tokpool is absent or empty is fully representable and round-trips. type DB struct { BasePath string Tree *Tree Meta *MetaFile TokCount uint32 // token entries in the .tokpool file, 0 when none HasTokFile bool } // OpenISKR opens base+".iskr" and, if it exists, base+".meta". A .tokpool that // is non-empty is an error: see DB. func OpenISKR(base string) (*DB, error) { t, err := OpenStoreTree(base + ".iskr") if err != nil { return nil, err } db := &DB{BasePath: base, Tree: t} metaPath := base + ".meta" if _, statErr := os.Stat(metaPath); statErr == nil { m, e := DecodeMetaFile(metaPath) if e != nil { t.Close() return nil, fmt.Errorf("lattice: %s: %w", metaPath, e) } db.Meta = m if uint32(len(m.Records)) != t.RecordCount() { t.Close() return nil, fmt.Errorf("lattice: %s has %d meta records but %s has %d records", metaPath, len(m.Records), base+".iskr", t.RecordCount()) } } tokPath := base + ".tokpool" if st, statErr := os.Stat(tokPath); statErr == nil { db.HasTokFile = true db.TokCount = uint32(st.Size() / 4) if db.TokCount > 0 { t.Close() 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) } } return db, nil } // Flush writes .meta atomically, then flushes the .iskr. The order is the // moxie one: a crash between the two leaves a .meta that the previous valid // .iskr can be re-derived from, never a .iskr no .meta describes. func (db *DB) Flush() error { if db.Meta != nil { if uint32(len(db.Meta.Records)) != db.Tree.RecordCount() { return fmt.Errorf("lattice: refusing to flush: .meta has %d records, tree has %d", len(db.Meta.Records), db.Tree.RecordCount()) } if err := EncodeMeta(db.BasePath+".meta", db.Meta, len(db.Meta.TokenPool) > 0); err != nil { return err } } return db.Tree.Flush() } // Close flushes then closes the tree. func (db *DB) Close() error { if err := db.Flush(); err != nil { return err } return db.Tree.Close() } // KeyVisitor is called for every key a Query reaches, in ascending key order // within a branch. Return false to stop that branch early. type KeyVisitor func(branch Branch, key Key, recIdx uint32, rec Record) bool // Query walks every block a root chain reaches, in key order within each // branch, and visits each key slot that names a record. This is what a lattice // query sees: the keys in files placed by whichever writer produced them are // only part of what the file holds when the writer detached blocks, so the // header distinguishes keys in blocks a root reaches (Queries) from keys held // only behind a record pointer (PlantKeys). // // A block whose key count exceeds C is read as C keys and C+1 children. func (t *Tree) Query(v KeyVisitor) error { for b := 0; b < C; b++ { if err := t.queryBranch(Branch(b), v); err != nil { return err } } return nil } func (t *Tree) queryBranch(branch Branch, v KeyVisitor) error { var walk func(idx uint32, depth int) error walk = func(idx uint32, depth int) error { if depth >= MaxTreeDepth { return errCycle("Query", branch) } n, err := t.GetNode(idx) if err != nil { return err } k := n.Count() leaf := n.Children[0] == NullIndex for i := 0; i < k; i++ { if !leaf { if err := walk(n.Children[i], depth+1); err != nil { return err } } ri := n.RecPtrs[i] if ri == NullRec || ri >= t.rCount { continue } rec, err := t.GetRecord(ri) if err != nil { return err } if !v(branch, n.Keys[i], ri, *rec) { return nil } } if !leaf { return walk(n.Children[k], depth+1) } return nil } return walk(t.Roots[branch], 0) } // PlantedQuery walks every key slot in every block, root chain or not, in // block index order, so a caller can check that all of them come back through // PlantedLookup. func (t *Tree) PlantedQuery(v KeyVisitor) error { for i := uint32(0); i < t.nCount; i++ { n, err := t.GetNode(i) if err != nil { return err } k := n.Count() for j := 0; j < k; j++ { ri := n.RecPtrs[j] if ri == NullRec || ri >= t.rCount { continue } rec, err := t.GetRecord(ri) if err != nil { return err } if !v(Branch(rec.Branch), n.Keys[j], ri, *rec) { return nil } } } return nil } // PlantedLookup finds a key by scanning every block of one branch, in block // order: the same result a Query of the whole branch gives for a key that sits // behind a record pointer, without trusting a separate index to say so. func (t *Tree) PlantedLookup(branch Branch, key Key) (recIdx uint32, rec *Record, err error) { for i := uint32(0); i < t.nCount; i++ { n, err := t.GetNode(i) if err != nil { return NullRec, nil, err } if n.GetBranch() != branch { continue } k := n.Count() for j := 0; j < k; j++ { if n.Keys[j] != key { continue } ri := n.RecPtrs[j] if ri == NullRec || ri >= t.rCount { return NullRec, nil, fmt.Errorf("lattice: block %d slot %d holds a null record pointer for key %#x", i, j, key) } r, err := t.GetRecord(ri) return ri, r, err } } return NullRec, nil, nil } // SampleKeys returns up to n reached (branch, key) pairs spread evenly over the // Query order, for a spot check that looks each one up again. func SampleKeys(t *Tree, n int) ([][2]uint64, error) { var all [][2]uint64 err := t.Query(func(branch Branch, key Key, recIdx uint32, rec Record) bool { all = append(all, [2]uint64{uint64(branch), uint64(key)}) return true }) if err != nil || len(all) == 0 { return nil, err } if n > len(all) { n = len(all) } out := make([][2]uint64, 0, n) step := len(all) / n if step < 1 { step = 1 } for i := 0; len(out) < n && i < len(all); i += step { out = append(out, all[i]) } return out, nil } // CopyToMemory reproduces t as a fresh in-memory tree with the same roots, // free list, blocks at the same indices, Mult and Flags, and record pointers // renumbered densely from 1 in record order. The returned map takes old record // indices to new. // // The renumbering exists for the MESH format, whose record index 0 is its null // pointer. It is wrong for a .iskr round trip: an .iskr stores record 0 // (iskra/storage.mx bound the old null test as recIdx >= rCount, which is always // false), and CopyToMemoryV5 does not renumber. Use CopyToMemoryV5 to write an // .iskr back. func (t *Tree) CopyToMemory() (*Tree, map[uint32]uint32, error) { dst := AllocTree(t.nCount, t.rCount+1, t.Roots) remap := make(map[uint32]uint32, t.rCount) for i := uint32(0); i < t.rCount; i++ { remap[i] = i + 1 } dst.rCount = t.rCount + 1 dst.FreeHead = t.FreeHead dst.FreeCount = t.FreeCount dst.Pending = append([]PendingExp(nil), t.Pending...) for i := uint32(0); i < t.nCount; i++ { n, err := t.GetNode(i) if err != nil { return nil, nil, err } c := *n for j := 0; j < C; j++ { if c.RecPtrs[j] == NullRec { continue } if c.RecPtrs[j] >= t.rCount { return nil, nil, fmt.Errorf("lattice: block %d slot %d holds record pointer %d beyond %d records", i, j, c.RecPtrs[j], t.rCount) } c.RecPtrs[j]++ } dst.Nodes[i] = c } for i := uint32(0); i < t.rCount; i++ { r, err := t.GetRecord(i) if err != nil { return nil, nil, err } c := *r for li := 0; li < 2; li++ { if c.Link[li] == NullRec || c.Link[li] == 0 { c.Link[li] = NullRec continue } if c.Link[li] >= t.rCount { return nil, nil, fmt.Errorf("lattice: record %d link %d points at %d beyond %d records", i, li, c.Link[li], t.rCount) } c.Link[li]++ } dst.Records[i+1] = c } dst.Records[0].Link = [2]uint32{NullRec, NullRec} dst.Meta = append([]MetaEntry(nil), t.Meta...) dst.Lex = append([]LexEntry(nil), t.Lex...) dst.Adj = append([]AdjLink(nil), t.Adj...) dst.StringPool = append([]byte(nil), t.StringPool...) dst.rebuildRecKey() return dst, remap, nil } // CopyToMemoryV5 copies every block and record of t into a fresh in-memory // tree exactly: same block indices, same record indices, the same 48 bytes per // record, the same roots, free list and journal. Nothing is renumbered, so a // tree written back from this copy has the same header it was read from. // // It copies every block, including blocks no root reaches, because a round trip // that dropped those would change the file it claims to preserve. func (t *Tree) CopyToMemoryV5() (*Tree, error) { dst := AllocTree(t.nCount, t.rCount, t.Roots) dst.rCount = t.rCount dst.FreeHead = t.FreeHead dst.FreeCount = t.FreeCount dst.Pending = append([]PendingExp(nil), t.Pending...) for i := uint32(0); i < t.nCount; i++ { n, err := t.GetNode(i) if err != nil { return nil, err } dst.Nodes[i] = *n } for i := uint32(0); i < t.rCount; i++ { r, err := t.GetRecord(i) if err != nil { return nil, err } dst.Records[i] = *r } dst.Meta = append([]MetaEntry(nil), t.Meta...) dst.Lex = append([]LexEntry(nil), t.Lex...) dst.Adj = append([]AdjLink(nil), t.Adj...) dst.StringPool = append([]byte(nil), t.StringPool...) dst.SourceVersion = Version dst.rebuildRecKey() return dst, nil } // SameAs reports the first difference between two trees, or nil when every // block (index, keys, record pointers, children, Mult, Flags), every record and // the roots, free list and journal are identical. func (t *Tree) SameAs(o *Tree) error { if t.nCount != o.nCount || t.rCount != o.rCount { return fmt.Errorf("block count %d/%d or record count %d/%d differs", t.nCount, o.nCount, t.rCount, o.rCount) } if t.Roots != o.Roots || t.FreeHead != o.FreeHead || t.FreeCount != o.FreeCount { return fmt.Errorf("roots, free head or free count differ") } if len(t.Pending) != len(o.Pending) { return fmt.Errorf("journal lengths differ") } for i := range t.Pending { if t.Pending[i] != o.Pending[i] { return fmt.Errorf("journal entry %d differs", i) } } for i := uint32(0); i < t.nCount; i++ { a, err := t.GetNode(i) if err != nil { return err } b, err := o.GetNode(i) if err != nil { return err } if *a != *b { return fmt.Errorf("block %d differs", i) } } for i := uint32(0); i < t.rCount; i++ { a, err := t.GetRecord(i) if err != nil { return err } b, err := o.GetRecord(i) if err != nil { return err } if *a != *b { return fmt.Errorf("record %d differs", i) } } return nil } // QueryDigest is a single number standing for the whole reachable key set, // record contents included, in Query order. func (t *Tree) QueryDigest() (uint64, int, error) { h := fnvOffset64 n := 0 buf := make([]byte, RecordSize) err := t.Query(func(branch Branch, key Key, recIdx uint32, rec Record) bool { encodeRecord(&rec, buf) h = fnv1(h, []byte{byte(branch)}) h = fnv1(h, le64(uint64(key))) h = fnv1(h, le64(uint64(recIdx))) h = fnv1(h, buf) n++ return true }) return h, n, err } // WriteISKRMemory writes an in-memory tree as base+".iskr" and, when meta is // non-nil, base+".meta", placing every key and record exactly where the tree // holds them. This is the writer gate 3 writes through. func WriteISKRMemory(base string, t *Tree, meta *MetaFile) error { if !t.IsMemory() { return fmt.Errorf("lattice: WriteISKRMemory needs an in-memory tree") } if meta != nil && uint32(len(meta.Records)) != t.rCount { return fmt.Errorf("lattice: .meta has %d records, tree has %d", len(meta.Records), t.rCount) } if err := SaveFile(base+".iskr", t); err != nil { return err } if meta != nil { if err := EncodeMeta(base+".meta", meta, len(meta.TokenPool) > 0); err != nil { return err } } return nil } // ReadISKRMemory reads base+".iskr" and base+".meta" into an in-memory tree, // placing every key and record exactly where the file holds them. It exists so // a .iskr can be read, written and re-read without the MESH format, which // needs a key index the .iskr does not store. func ReadISKRMemory(base string) (*Tree, *MetaFile, error) { t, err := LoadFile(base + ".iskr") if err != nil { return nil, nil, err } metaPath := base + ".meta" if _, statErr := os.Stat(metaPath); statErr == nil { m, e := DecodeMetaFile(metaPath) if e != nil { return nil, nil, e } if uint32(len(m.Records)) != t.rCount { return nil, nil, fmt.Errorf("lattice: %s has %d records, %s has %d", metaPath, len(m.Records), base+".iskr", t.rCount) } return t, m, nil } return t, nil, nil } // sortedBranchKeys returns every reached (branch,key) pair, ascending. func sortedBranchKeys(t *Tree) ([][2]uint64, error) { var out [][2]uint64 err := t.Query(func(branch Branch, key Key, recIdx uint32, rec Record) bool { out = append(out, [2]uint64{uint64(branch), uint64(key)}) return true }) sort.Slice(out, func(i, j int) bool { if out[i][0] != out[j][0] { return out[i][0] < out[j][0] } return out[i][1] < out[j][1] }) return out, err } func max(a, b int) int { if a > b { return a } return b } // FileSizeOnDisk is the size of the tree's file, or 0 for an in-memory tree. func (t *Tree) FileSizeOnDisk() (int64, error) { if t.Store == nil { return 0, nil } st, err := t.Store.File().Stat() if err != nil { return 0, err } return st.Size(), nil }