forked from KurokuLabs/margo
/
bolt.go
129 lines (111 loc) · 2.4 KB
/
bolt.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
package bolt
import (
"bytes"
"fmt"
bolt "github.com/coreos/bbolt"
"github.com/ugorji/go/codec"
"io/ioutil"
"os"
"path/filepath"
"reflect"
"sync"
"time"
)
var (
DS = func() *DataStore {
dir := os.Getenv("MARGO_DATA_DIR")
if dir == "" {
d, err := ioutil.TempDir("", "margo.data~fallback~")
if err != nil {
panic("MARGO_DATA_DIR is not defined and ioutill.TempDir failed: " + err.Error())
}
dir = d
}
return &DataStore{
Path: filepath.Join(dir, "bolt.ds"),
Handle: &codec.MsgpackHandle{},
Bucket: []byte("ds"),
}
}()
)
type DataStore struct {
Bucket []byte
Handle codec.Handle
Path string
mu sync.RWMutex
}
func (ds *DataStore) encodeKey(v interface{}) []byte {
pkg := ""
if t := reflect.TypeOf(v); t != nil {
pkg = t.PkgPath()
}
buf := &bytes.Buffer{}
fmt.Fprintf(buf, "pkg=%s typ=%T str=%#v", pkg, v, v)
return buf.Bytes()
}
func (ds *DataStore) encodeVal(v interface{}) ([]byte, error) {
s := []byte{}
err := codec.NewEncoderBytes(&s, ds.Handle).Encode(v)
return s, err
}
func (ds *DataStore) decodeVal(s []byte, p interface{}) error {
return codec.NewDecoderBytes(s, ds.Handle).Decode(p)
}
func (ds *DataStore) view(f func(*bolt.Tx) error) error {
ds.mu.RLock()
defer ds.mu.RUnlock()
return ds.tx(true, f)
}
func (ds *DataStore) update(f func(*bolt.Tx) error) error {
ds.mu.Lock()
defer ds.mu.Unlock()
return ds.tx(false, f)
}
func (ds *DataStore) tx(view bool, f func(*bolt.Tx) error) error {
db, err := bolt.Open(ds.Path, 0600, &bolt.Options{
Timeout: 5 * time.Second,
})
if err != nil {
return err
}
defer db.Close()
if view {
return db.View(f)
}
return db.Update(f)
}
func (ds *DataStore) Load(key, ptr interface{}) error {
k := ds.encodeKey(key)
return ds.view(func(tx *bolt.Tx) error {
bck := tx.Bucket(ds.Bucket)
if bck == nil {
return bolt.ErrBucketNotFound
}
s := bck.Get(k)
return ds.decodeVal(s, ptr)
})
}
func (ds *DataStore) Store(key, val interface{}) error {
k := ds.encodeKey(key)
v, err := ds.encodeVal(val)
if err != nil {
return err
}
return ds.update(func(tx *bolt.Tx) error {
bck, err := tx.CreateBucketIfNotExists(ds.Bucket)
if err != nil {
return err
}
return bck.Put(k, v)
})
}
func (ds *DataStore) Delete(key interface{}) error {
k := ds.encodeKey(key)
return ds.update(func(tx *bolt.Tx) error {
bck := tx.Bucket(ds.Bucket)
if bck == nil {
return nil
}
return bck.Delete(k)
})
}