storage.go raw
1 package iskra
2
3 import (
4 "encoding/binary"
5 "errors"
6 "fmt"
7 "os"
8 "path/filepath"
9
10 "git.smesh.lol/go-iskra/lattice"
11 )
12
13 // Storage is one iskra database: base.iskr, base.meta, base.tokpool.
14 type Storage struct {
15 Base string
16 T *Tree
17 Bytes int64 // .iskr size at the last open or flush
18 }
19
20 // StorageCreate makes a new, empty base path.
21 func StorageCreate(base string) (*Storage, error) {
22 t, err := lattice.Create(base + ".iskr")
23 if err != nil {
24 return nil, err
25 }
26 s := &Storage{Base: base, T: NewTree(t)}
27 if err := os.WriteFile(base+".tokpool", nil, 0o644); err != nil {
28 t.Close()
29 return nil, err
30 }
31 if err := s.flushMeta(nil); err != nil {
32 t.Close()
33 return nil, err
34 }
35 return s, nil
36 }
37
38 // StorageOpen opens base.iskr with its .meta and .tokpool companions.
39 func StorageOpen(base string) (*Storage, error) {
40 t, err := lattice.OpenStoreTree(base + ".iskr")
41 if err != nil {
42 return nil, err
43 }
44 s := &Storage{Base: base, T: NewTree(t)}
45 s.Bytes, _ = t.FileSizeOnDisk()
46 meta, err := lattice.DecodeMetaFile(base + ".meta")
47 if err == nil {
48 if uint32(len(meta.Records)) > t.RecordCount() {
49 t.Close()
50 return nil, fmt.Errorf("iskra: %s.meta has %d records, %s.iskr has %d", base, len(meta.Records), base, t.RecordCount())
51 }
52 s.T.RecMeta = meta.Records
53 s.T.StringPool = meta.StringPool
54 s.T.TokenPool = meta.TokenPool
55 for i := range meta.Dict {
56 d := &meta.Dict[i]
57 end := uint64(d.Offset) + uint64(d.Len)
58 if end > uint64(len(meta.DictPool)) {
59 t.Close()
60 return nil, fmt.Errorf("iskra: %s.meta dict entry %d runs past the pool", base, i)
61 }
62 word := string(meta.DictPool[d.Offset:end])
63 if _, seen := s.T.Dict.Index[word]; seen {
64 continue
65 }
66 idx := uint32(len(s.T.Dict.Entries))
67 s.T.Dict.Pool = append(s.T.Dict.Pool, word...)
68 s.T.Dict.Entries = append(s.T.Dict.Entries, DictEntry{
69 Offset: d.Offset, Len: d.Len, Class: d.Class, Count: d.Count,
70 })
71 s.T.Dict.Index[word] = idx
72 }
73 } else if !errors.Is(err, os.ErrNotExist) {
74 t.Close()
75 return nil, fmt.Errorf("iskra: %s.meta: %w", base, err)
76 }
77 // The token pool lives in .meta when the writer put it there (this Go
78 // writer does) and in .tokpool when the moxie writer did. Both are read:
79 // .tokpool, when it exists and is not empty, is the authority, and the
80 // .meta copy is used only when .tokpool is absent or empty.
81 tokPath := base + ".tokpool"
82 var tokBytes int64
83 if st, statErr := os.Stat(tokPath); statErr == nil {
84 s.T.TokFile = true
85 tokBytes = st.Size()
86 }
87 if tokBytes > 0 {
88 raw, err := os.ReadFile(tokPath)
89 if err != nil {
90 t.Close()
91 return nil, err
92 }
93 if len(raw)%4 != 0 {
94 t.Close()
95 return nil, fmt.Errorf("iskra: %s is %d bytes, not a whole number of uint32 tokens", tokPath, len(raw))
96 }
97 s.T.TokenPool = make([]uint32, len(raw)/4)
98 for i := range s.T.TokenPool {
99 s.T.TokenPool[i] = binary.LittleEndian.Uint32(raw[i*4:])
100 }
101 }
102 if len(s.T.TokenPool) == 0 {
103 if m, err := ReadMetaFile(base + ".meta"); err == nil && len(m.TokenPool) > 0 {
104 s.T.TokenPool = m.TokenPool
105 }
106 }
107 s.T.RebuildSigIdx()
108 return s, nil
109 }
110
111 // ReadDBBase returns the base path of a .iskr or .iskr5 file: an extension
112 // ending in "iskr" is removed, and a translated file reports its own base.
113 func ReadDBBase(path string) string {
114 for _, suffix := range []string{".iskr", ".iskr5"} {
115 if len(path) > len(suffix) && path[len(path)-len(suffix):] == suffix {
116 return path[:len(path)-len(suffix)]
117 }
118 }
119 return path
120 }
121
122 // flushMeta writes .meta atomically. The .meta holds the dictionary and the
123 // token pool, so a freshly created or grown database needs no .tokpool file to
124 // reload; .tokpool is written as well for compatibility with the moxie reader.
125 func (s *Storage) flushMeta(_ *Tree) error {
126 t := s.T
127 if uint32(len(t.RecMeta)) < t.DB.RecordCount() {
128 return fmt.Errorf("iskra: refusing to flush: %d meta records for %d lattice records", len(t.RecMeta), t.DB.RecordCount())
129 }
130 meta := &lattice.MetaFile{
131 Records: t.RecMeta[:t.DB.RecordCount()],
132 StringPool: t.StringPool,
133 TokenPool: t.TokenPool,
134 }
135 meta.Dict = make([]lattice.DictEntry, len(t.Dict.Entries))
136 meta.DictPool = t.Dict.Pool
137 for i, e := range t.Dict.Entries {
138 meta.Dict[i] = lattice.DictEntry{Offset: e.Offset, Len: e.Len, Class: e.Class, Count: e.Count}
139 }
140 return lattice.EncodeMeta(s.Base+".meta", meta, true)
141 }
142
143 // Flush writes .tokpool, .meta, then flushes .iskr.
144 func (s *Storage) Flush() error {
145 if s.T.TokFile {
146 buf := make([]byte, len(s.T.TokenPool)*4)
147 for i, v := range s.T.TokenPool {
148 binary.LittleEndian.PutUint32(buf[i*4:], v)
149 }
150 if err := os.WriteFile(s.Base+".tokpool", buf, 0o644); err != nil {
151 return err
152 }
153 }
154 if err := s.flushMeta(nil); err != nil {
155 return err
156 }
157 if err := s.T.DB.Flush(); err != nil {
158 return err
159 }
160 s.Bytes, _ = s.T.DB.FileSizeOnDisk()
161 return nil
162 }
163
164 // Close flushes and closes the lattice.
165 func (s *Storage) Close() error {
166 if err := s.Flush(); err != nil {
167 return err
168 }
169 return s.T.DB.Close()
170 }
171
172 // SuffixOf joins a directory and a name with a separator, for base paths that
173 // are chosen dynamically.
174 func BaseOf(dir, name string) string { return filepath.Join(dir, name) }
175