forked from sei-protocol/sei-iavl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
orphandb.go
75 lines (69 loc) · 1.81 KB
/
orphandb.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
package iavl
import (
"fmt"
"io/fs"
"io/ioutil"
"os"
"path"
"strings"
)
type orphanDB struct {
cache map[int64]map[string]int64 // key: version, value: orphans
directory string
numOrphansPerFile int
}
func NewOrphanDB(opts *Options) *orphanDB {
return &orphanDB{
cache: map[int64]map[string]int64{},
directory: opts.OrphanDirectory,
numOrphansPerFile: opts.NumOrphansPerFile,
}
}
func (o *orphanDB) SaveOrphans(version int64, orphans map[string]int64) error {
o.cache[version] = orphans
chunks := [][]string{{}}
for orphan := range orphans {
if len(chunks[len(chunks)-1]) == o.numOrphansPerFile {
chunks = append(chunks, []string{})
}
chunks[len(chunks)-1] = append(chunks[len(chunks)-1], orphan)
}
dir := path.Join(o.directory, fmt.Sprintf("%d", version))
os.RemoveAll(dir)
os.MkdirAll(dir, fs.ModePerm)
for i, chunk := range chunks {
f, err := os.Create(path.Join(dir, fmt.Sprintf("%d", i)))
if err != nil {
return err
}
f.WriteString(strings.Join(chunk, "\n"))
f.Close()
}
return nil
}
func (o *orphanDB) GetOrphans(version int64) map[string]int64 {
if _, ok := o.cache[version]; !ok {
o.cache[version] = map[string]int64{}
dir := path.Join(o.directory, fmt.Sprintf("%d", version))
files, err := ioutil.ReadDir(dir)
if err != nil {
// no orphans found
return o.cache[version]
}
for _, file := range files {
content, err := ioutil.ReadFile(path.Join(dir, file.Name()))
if err != nil {
return o.cache[version]
}
for _, orphan := range strings.Split(string(content), "\n") {
o.cache[version][orphan] = version
}
}
}
return o.cache[version]
}
func (o *orphanDB) DeleteOrphans(version int64) error {
delete(o.cache, version)
dir := path.Join(o.directory, fmt.Sprintf("%d", version))
return os.RemoveAll(dir)
}