/
file.go
418 lines (344 loc) · 8.95 KB
/
file.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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Original source: github.com/micro/go-micro/v3/store/file/file.go
// Package local is a file system backed store
package file
import (
"bytes"
"encoding/json"
"os"
"path/filepath"
"time"
"github.com/micro/micro/v3/service/store"
bolt "go.etcd.io/bbolt"
)
var (
// DefaultDatabase is the namespace that the bbolt store
// will use if no namespace is provided.
DefaultDatabase = "micro"
// DefaultTable when none is specified
DefaultTable = "micro"
// DefaultDir is the default directory for bbolt files
DefaultDir = filepath.Join(os.TempDir(), "micro", "store")
// bucket used for data storage
dataBucket = "data"
)
// NewStore returns a file store
func NewStore(opts ...store.Option) store.Store {
s := &fileStore{}
s.init(opts...)
return s
}
type fileStore struct {
options store.Options
dir string
}
type fileHandle struct {
key string
db *bolt.DB
}
// record stored by us
type record struct {
Key string
Value []byte
Metadata map[string]interface{}
ExpiresAt time.Time
}
func key(database, table string) string {
return database + ":" + table
}
func (m *fileStore) delete(db *bolt.DB, key string) error {
return db.Update(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(dataBucket))
if b == nil {
return nil
}
return b.Delete([]byte(key))
})
}
func (m *fileStore) init(opts ...store.Option) error {
for _, o := range opts {
o(&m.options)
}
if m.options.Database == "" {
m.options.Database = DefaultDatabase
}
if m.options.Table == "" {
// bbolt requires bucketname to not be empty
m.options.Table = DefaultTable
}
// Ignoring this as the folder might exist.
// Reads/Writes updates will return with sensible error messages
// about the dir not existing in case this cannot create the path anyway
dir := m.getDir(m.options.Database)
os.MkdirAll(dir, 0700)
return nil
}
// getDir returns the directory which should contain the files for a databases
func (m *fileStore) getDir(db string) string {
// get the directory option from the context
var directory string
if m.options.Context != nil {
fd, ok := m.options.Context.Value(dirKey{}).(string)
if ok {
directory = fd
}
}
if len(directory) == 0 {
directory = DefaultDir
}
// construct the directory, e.g. /tmp/micro
return filepath.Join(directory, db)
}
func (f *fileStore) getDB(database, table string) (*bolt.DB, error) {
if len(database) == 0 {
database = f.options.Database
}
if len(table) == 0 {
table = f.options.Table
}
// create a directory /tmp/micro
dir := f.getDir(database)
// create the database handle
fname := table + ".db"
// make the dir
os.MkdirAll(dir, 0700)
// database path
dbPath := filepath.Join(dir, fname)
// create new db handle
// Bolt DB only allows one process to open the file R/W so make sure we're doing this under a lock
return bolt.Open(dbPath, 0700, &bolt.Options{Timeout: 5 * time.Second})
}
func (m *fileStore) list(db *bolt.DB, order store.Order, limit, offset uint, prefix, suffix string) []string {
var keys []string
db.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(dataBucket))
// nothing to read
if b == nil {
return nil
}
c := b.Cursor()
var k, v []byte
var cont func(k []byte) bool
if prefix != "" {
// for prefix we can speed up the search, not for suffix though :(
k, v = c.Seek([]byte(prefix))
cont = func(k []byte) bool {
return bytes.HasPrefix(k, []byte(prefix))
}
} else {
k, v = c.First()
cont = func(k []byte) bool {
return true
}
}
// get all the key/vals
for ; k != nil && cont(k); k, v = c.Next() {
storedRecord := &record{}
if err := json.Unmarshal(v, storedRecord); err != nil {
return err
}
if !storedRecord.ExpiresAt.IsZero() {
if storedRecord.ExpiresAt.Before(time.Now()) {
continue
}
}
if suffix != "" && !bytes.HasSuffix(k, []byte(suffix)) {
continue
}
keys = append(keys, string(k))
}
return nil
})
// now check if we need do ordering
if order == store.OrderDesc {
for i, j := 0, len(keys)-1; i < j; i, j = i+1, j-1 {
keys[i], keys[j] = keys[j], keys[i]
}
}
// build a new key set
var keyList []string
if offset > 0 {
// offset is greater than the keys we have
if int(offset) >= len(keys) {
return nil
}
// otherwise set the offset for the keys
keys = keys[offset:]
}
// check key limit
if v := int(limit); v == 0 || v > len(keys) {
limit = uint(len(keys))
}
for i := 0; i < int(limit); i++ {
keyList = append(keyList, keys[i])
}
return keyList
}
func (m *fileStore) get(db *bolt.DB, k string) (*store.Record, error) {
var value []byte
db.View(func(tx *bolt.Tx) error {
// @todo this is still very experimental...
b := tx.Bucket([]byte(dataBucket))
if b == nil {
return nil
}
value = b.Get([]byte(k))
return nil
})
if value == nil {
return nil, store.ErrNotFound
}
storedRecord := &record{}
if err := json.Unmarshal(value, storedRecord); err != nil {
return nil, err
}
newRecord := &store.Record{}
newRecord.Key = storedRecord.Key
newRecord.Value = storedRecord.Value
newRecord.Metadata = make(map[string]interface{})
for k, v := range storedRecord.Metadata {
newRecord.Metadata[k] = v
}
if !storedRecord.ExpiresAt.IsZero() {
if storedRecord.ExpiresAt.Before(time.Now()) {
return nil, store.ErrNotFound
}
newRecord.Expiry = time.Until(storedRecord.ExpiresAt)
}
return newRecord, nil
}
func (m *fileStore) set(db *bolt.DB, r *store.Record) error {
// copy the incoming record and then
// convert the expiry in to a hard timestamp
item := &record{}
item.Key = r.Key
item.Value = r.Value
item.Metadata = make(map[string]interface{})
if r.Expiry != 0 {
item.ExpiresAt = time.Now().Add(r.Expiry)
}
for k, v := range r.Metadata {
item.Metadata[k] = v
}
// marshal the data
data, _ := json.Marshal(item)
return db.Update(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(dataBucket))
if b == nil {
var err error
b, err = tx.CreateBucketIfNotExists([]byte(dataBucket))
if err != nil {
return err
}
}
return b.Put([]byte(r.Key), data)
})
}
func (f *fileStore) Close() error {
return nil
}
func (f *fileStore) Init(opts ...store.Option) error {
return f.init(opts...)
}
func (m *fileStore) Delete(key string, opts ...store.DeleteOption) error {
var deleteOptions store.DeleteOptions
for _, o := range opts {
o(&deleteOptions)
}
db, err := m.getDB(deleteOptions.Database, deleteOptions.Table)
if err != nil {
return err
}
defer db.Close()
return m.delete(db, key)
}
func (m *fileStore) Read(key string, opts ...store.ReadOption) ([]*store.Record, error) {
var readOpts store.ReadOptions
for _, o := range opts {
o(&readOpts)
}
db, err := m.getDB(readOpts.Database, readOpts.Table)
if err != nil {
return nil, err
}
defer db.Close()
var keys []string
// Handle Prefix / suffix
if readOpts.Prefix || readOpts.Suffix {
prefix := ""
if readOpts.Prefix {
prefix = key
}
suffix := ""
if readOpts.Suffix {
suffix = key
}
// list the keys
keys = m.list(db, readOpts.Order, readOpts.Limit, readOpts.Offset, prefix, suffix)
} else {
keys = []string{key}
}
var results []*store.Record
for _, k := range keys {
r, err := m.get(db, k)
if err != nil {
return results, err
}
results = append(results, r)
}
return results, nil
}
func (m *fileStore) Write(r *store.Record, opts ...store.WriteOption) error {
var writeOpts store.WriteOptions
for _, o := range opts {
o(&writeOpts)
}
db, err := m.getDB(writeOpts.Database, writeOpts.Table)
if err != nil {
return err
}
defer db.Close()
if len(opts) > 0 {
// Copy the record before applying options, or the incoming record will be mutated
newRecord := store.Record{}
newRecord.Key = r.Key
newRecord.Value = r.Value
newRecord.Metadata = make(map[string]interface{})
newRecord.Expiry = r.Expiry
for k, v := range r.Metadata {
newRecord.Metadata[k] = v
}
return m.set(db, &newRecord)
}
return m.set(db, r)
}
func (m *fileStore) Options() store.Options {
return m.options
}
func (m *fileStore) List(opts ...store.ListOption) ([]string, error) {
var listOptions store.ListOptions
for _, o := range opts {
o(&listOptions)
}
db, err := m.getDB(listOptions.Database, listOptions.Table)
if err != nil {
return nil, err
}
defer db.Close()
allKeys := m.list(db, listOptions.Order, listOptions.Limit, listOptions.Offset, listOptions.Prefix, listOptions.Suffix)
return allKeys, nil
}
func (m *fileStore) String() string {
return "file"
}