-
Notifications
You must be signed in to change notification settings - Fork 127
/
badger.go
73 lines (66 loc) · 1.34 KB
/
badger.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
package storage
import (
"time"
"github.com/dgraph-io/badger"
)
type BadgerStore struct {
snapshotsDB *badger.DB
cacheDB *badger.DB
stateDB *badger.DB
queue *Queue
closing bool
}
func NewBadgerStore(dir string) (*BadgerStore, error) {
snapshotsDB, err := openDB(dir+"/snapshots", true)
if err != nil {
return nil, err
}
cacheDB, err := openDB(dir+"/cache", true)
if err != nil {
return nil, err
}
stateDB, err := openDB(dir+"/state", true)
if err != nil {
return nil, err
}
return &BadgerStore{
snapshotsDB: snapshotsDB,
cacheDB: cacheDB,
stateDB: stateDB,
queue: NewQueue(),
closing: false,
}, nil
}
func (store *BadgerStore) Close() error {
store.closing = true
store.queue.Dispose()
err := store.snapshotsDB.Close()
if err != nil {
return err
}
err = store.stateDB.Close()
if err != nil {
return err
}
return store.cacheDB.Close()
}
func openDB(dir string, sync bool) (*badger.DB, error) {
opts := badger.DefaultOptions(dir)
opts.SyncWrites = sync
db, err := badger.Open(opts)
if err != nil {
return nil, err
}
db.RunValueLogGC(0.1)
go func() {
ticker := time.NewTicker(1 * time.Minute)
defer ticker.Stop()
for range ticker.C {
lsm, vlog := db.Size()
if lsm > 1024*1024*8 || vlog > 1024*1024*32 {
db.RunValueLogGC(0.5)
}
}
}()
return db, nil
}