-
Notifications
You must be signed in to change notification settings - Fork 9
/
store.go
288 lines (247 loc) · 6.83 KB
/
store.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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
// Package stow is used to persist objects to a bolt.DB database.
package stow
import (
"bytes"
"errors"
"sync"
bolt "go.etcd.io/bbolt"
)
var pool = &sync.Pool{
New: func() interface{} { return bytes.NewBuffer(nil) },
}
// ErrNotFound indicates object is not in database.
var ErrNotFound = errors.New("not found")
// Store manages objects persistence.
type Store struct {
db *bolt.DB
bucket bucketSpec
codec Codec
}
// NewStore creates a new Store, using the underlying
// bolt.DB "bucket" to persist objects.
// NewStore uses GobEncoding, your objects must be registered
// via gob.Register() for this encoding to work.
func NewStore(db *bolt.DB, bucket []byte) *Store {
return NewCustomStore(db, bucket, GobCodec{})
}
// NewJSONStore creates a new Store, using the underlying
// bolt.DB "bucket" to persist objects as json.
func NewJSONStore(db *bolt.DB, bucket []byte) *Store {
return NewCustomStore(db, bucket, JSONCodec{})
}
// NewXMLStore creates a new Store, using the underlying
// bolt.DB "bucket" to persist objects as xml.
func NewXMLStore(db *bolt.DB, bucket []byte) *Store {
return NewCustomStore(db, bucket, XMLCodec{})
}
// NewCustomStore allows you to create a store with
// a custom underlying Encoding
func NewCustomStore(db *bolt.DB, bucket []byte, codec Codec) *Store {
return &Store{db: db, bucket: bucketSpec{bucket}, codec: codec}
}
// NewNestedStore returns a new Store which is nested inside the current store's
// bucket. It inherits the original store's Codec, and will be deleted by the parent
// store's DeleteAll method. Also note that buckets are in the parents key-space so
// you cannot have a NestedStore whose "bucket" is the same as a parent's key.
func (s *Store) NewNestedStore(bucket []byte) *Store {
return s.NewCustomNestedStore(bucket, s.codec)
}
// NewCustomNestedStore works the same as NewNestedStore except you can override the
// Codec used by the returned Store.
func (s *Store) NewCustomNestedStore(bucket []byte, codec Codec) *Store {
return &Store{
db: s.db,
bucket: append(s.bucket, bucket),
codec: codec,
}
}
func (s *Store) marshal(val interface{}) (data []byte, err error) {
buf := pool.Get().(*bytes.Buffer)
enc := s.codec.NewEncoder(buf)
err = enc.Encode(val)
data = append(data, buf.Bytes()...)
buf.Reset()
pool.Put(buf)
if pCodec, ok := s.codec.(*pooledCodec); ok && err == nil {
pCodec.PutEncoder(enc)
}
return data, err
}
func (s *Store) unmarshal(data []byte, val interface{}) (err error) {
dec := s.codec.NewDecoder(bytes.NewReader(data))
err = dec.Decode(val)
if pCodec, ok := s.codec.(*pooledCodec); ok && err == nil {
pCodec.PutDecoder(dec)
}
return err
}
func (s *Store) toBytes(key interface{}) (keyBytes []byte, err error) {
switch k := key.(type) {
case string:
return []byte(k), nil
case []byte:
return k, nil
default:
return s.marshal(key)
}
}
// Put will store b with key "key". If key is []byte or string it uses the key
// directly. Otherwise, it marshals the given type into bytes using the stores Encoder.
func (s *Store) Put(key interface{}, b interface{}) error {
keyBytes, err := s.toBytes(key)
if err != nil {
return err
}
return s.put(keyBytes, b)
}
// Put will store b with key "key". If key is []byte or string it uses the key
// directly. Otherwise, it marshals the given type into bytes using the stores Encoder.
func (s *Store) put(key []byte, b interface{}) (err error) {
var data []byte
data, err = s.marshal(b)
if err != nil {
return err
}
return s.db.Update(func(tx *bolt.Tx) error {
objects, err := s.bucket.createOrGet(tx)
if err != nil {
return err
}
return objects.Put(key, data)
})
}
// Pull will retrieve b with key "key", and removes it from the store.
func (s *Store) Pull(key interface{}, b interface{}) error {
keyBytes, err := s.toBytes(key)
if err != nil {
return err
}
return s.pull(keyBytes, b)
}
// Pull will retrieve b with key "key", and removes it from the store.
func (s *Store) pull(key []byte, b interface{}) error {
buf := pool.Get().(*bytes.Buffer)
defer func() {
buf.Reset()
pool.Put(buf)
}()
err := s.db.Update(func(tx *bolt.Tx) error {
objects := s.bucket.get(tx)
if objects == nil {
return ErrNotFound
}
data := objects.Get(key)
if data == nil {
return ErrNotFound
}
buf.Write(data)
return objects.Delete(key)
})
if err != nil {
return err
}
return s.unmarshal(buf.Bytes(), b)
}
// Get will retrieve b with key "key". If key is []byte or string it uses the key
// directly. Otherwise, it marshals the given type into bytes using the stores Encoder.
func (s *Store) Get(key interface{}, b interface{}) error {
keyBytes, err := s.toBytes(key)
if err != nil {
return err
}
return s.get(keyBytes, b)
}
// Get will retrieve b with key "key"
func (s *Store) get(key []byte, b interface{}) error {
buf := bytes.NewBuffer(nil)
err := s.db.View(func(tx *bolt.Tx) error {
objects := s.bucket.get(tx)
if objects == nil {
return ErrNotFound
}
data := objects.Get(key)
if data == nil {
return ErrNotFound
}
buf.Write(data)
return nil
})
if err != nil {
return err
}
return s.unmarshal(buf.Bytes(), b)
}
// ForEach will run do on each object in the store.
// do can be a function which takes either: 1 param which will take on each "value"
// or 2 params where the first param is the "key" and the second is the "value".
func (s *Store) ForEach(do interface{}) error {
fc, err := newFuncCall(s, do)
if err != nil {
return err
}
return s.db.View(func(tx *bolt.Tx) error {
objects := s.bucket.get(tx)
if objects == nil {
return nil
}
return objects.ForEach(fc.call)
})
}
// DeleteAll empties the store
func (s *Store) DeleteAll() error {
return s.db.Update(s.bucket.delete)
}
// Delete will remove the item with the specified key from the store.
// It returns nil if the item was not found (like BoltDB).
func (s *Store) Delete(key interface{}) error {
keyBytes, err := s.toBytes(key)
if err != nil {
return err
}
return s.db.Update(func(tx *bolt.Tx) error {
objects := s.bucket.get(tx)
if objects == nil {
return nil
}
return objects.Delete(keyBytes)
})
}
type bucketSpec [][]byte
func (bs bucketSpec) get(tx *bolt.Tx) (bt *bolt.Bucket) {
for _, b := range bs {
if bt != nil {
bt = bt.Bucket(b)
} else {
bt = tx.Bucket(b)
}
if bt == nil {
break
}
}
return bt
}
func (bs bucketSpec) createOrGet(tx *bolt.Tx) (bt *bolt.Bucket, err error) {
for _, b := range bs {
if bt != nil {
bt, err = bt.CreateBucketIfNotExists(b)
} else {
bt, err = tx.CreateBucketIfNotExists(b)
}
if bt == nil || err != nil {
break
}
}
return bt, err
}
func (bs bucketSpec) delete(tx *bolt.Tx) (err error) {
switch len(bs) {
case 0:
return nil
case 1:
return tx.DeleteBucket(bs[0])
default:
lastParentBucket := bs[:len(bs)-1]
childBucketName := bs[len(bs)-1]
return lastParentBucket.get(tx).DeleteBucket(childBucketName)
}
}