/
leveldb.go
87 lines (69 loc) · 2.13 KB
/
leveldb.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
package leveldb
import (
"fmt"
"github.com/0xPolygon/polygon-edge/blockchain/storage"
"github.com/hashicorp/go-hclog"
"github.com/syndtr/goleveldb/leveldb"
"github.com/syndtr/goleveldb/leveldb/opt"
)
const (
DefaultCache = int(256)
DefaultHandles = int(256)
)
// Factory creates a leveldb storage
func Factory(config map[string]interface{}, logger hclog.Logger) (storage.Storage, error) {
path, ok := config["path"]
if !ok {
return nil, fmt.Errorf("path not found")
}
pathStr, ok := path.(string)
if !ok {
return nil, fmt.Errorf("path is not a string")
}
return NewLevelDBStorage(pathStr, logger)
}
// NewLevelDBStorage creates the new storage reference with leveldb default options
func NewLevelDBStorage(path string, logger hclog.Logger) (storage.Storage, error) {
// Set default options
options := &opt.Options{
OpenFilesCacheCapacity: DefaultHandles,
BlockCacheCapacity: DefaultCache / 2 * opt.MiB,
WriteBuffer: DefaultCache / 4 * opt.MiB, // Two of these are used internally
}
return NewLevelDBStorageWithOpt(path, logger, options)
}
// NewLevelDBStorageWithOpt creates the new storage reference with leveldb with custom options
func NewLevelDBStorageWithOpt(path string, logger hclog.Logger, opts *opt.Options) (storage.Storage, error) {
db, err := leveldb.OpenFile(path, opts)
if err != nil {
return nil, err
}
kv := &levelDBKV{db}
return storage.NewKeyValueStorage(logger.Named("leveldb"), kv), nil
}
// levelDBKV is the leveldb implementation of the kv storage
type levelDBKV struct {
db *leveldb.DB
}
// Set sets the key-value pair in leveldb storage
func (l *levelDBKV) Set(p []byte, v []byte) error {
return l.db.Put(p, v, nil)
}
// Get retrieves the key-value pair in leveldb storage
func (l *levelDBKV) Get(p []byte) ([]byte, bool, error) {
data, err := l.db.Get(p, nil)
if err != nil {
if err.Error() == "leveldb: not found" {
return nil, false, nil
}
return nil, false, err
}
return data, true, nil
}
// Close closes the leveldb storage instance
func (l *levelDBKV) Close() error {
return l.db.Close()
}
func (l *levelDBKV) NewBatch() storage.Batch {
return NewBatchLevelDB(l.db)
}