-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathesdb.go
91 lines (74 loc) · 1.55 KB
/
esdb.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
package esdb
import (
"bytes"
"os"
"sync"
"github.com/customerio/esdb/binary"
"github.com/customerio/esdb/bounded"
"github.com/customerio/esdb/sst"
)
// TODO Verify(file string) bool
type Db struct {
file *os.File
index *sst.Reader
locations map[string][]int64
calcLocations sync.Once
}
// Opens a .esdb file for reading.
func Open(path string) (*Db, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
st, err := findIndex(file)
if err != nil {
return nil, err
}
return &Db{
file: file,
index: st,
}, nil
}
// Finds and returns a space by it's id.
func (db *Db) Find(id []byte) *Space {
if val, err := db.index.Get(id); err == nil {
b := bytes.NewReader(val)
// The entry in the SSTable index is
// the offset and length of the space
// within the file.
offset := binary.ReadInt64(b)
length := binary.ReadInt64(b)
return openSpace(
db.file,
id,
offset,
length,
)
}
return nil
}
// Iterates and returns each defined space.
func (db *Db) Iterate(process func(s *Space) bool) error {
if iter, err := db.index.Find([]byte("")); err == nil {
for iter.Next() {
if !process(db.Find(iter.Key())) {
break
}
}
return nil
} else {
return err
}
}
func (db *Db) Close() {
if db.file != nil {
db.file.Close()
}
}
func findIndex(f *os.File) (*sst.Reader, error) {
// The last 8 bytes in the file is the length
// of the SSTable spaces index.
f.Seek(-8, 2)
indexLen := binary.ReadInt64(f)
return sst.NewReader(bounded.New(f, -8-indexLen, -8), indexLen)
}