-
Notifications
You must be signed in to change notification settings - Fork 1
/
db.go
111 lines (99 loc) · 2.06 KB
/
db.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
package kv
import (
"context"
"encoding/json"
iflog "github.com/IceFireDB/icefiredb-ipfs-log"
cache "github.com/patrickmn/go-cache"
"go.uber.org/zap"
)
const UnDefStr = ""
type KeyValueDB struct {
ev *iflog.IpfsLog
db *cache.Cache
log *zap.Logger
}
func NewKeyValueDB(ctx context.Context, ev *iflog.IpfsLog, log *zap.Logger) (*KeyValueDB, error) {
db := cache.New(0, 0)
kv := KeyValueDB{
ev: ev,
db: db,
log: log,
}
if err := kv.syncData(ctx); err != nil {
return nil, err
}
return &kv, nil
}
func (kv *KeyValueDB) syncData(ctx context.Context) error {
ch, err := kv.ev.WatchWriteEvent(ctx)
if err != nil {
return err
}
go func() {
var data []byte
var opr operation
for {
select {
case <-ctx.Done():
return
case data = <-ch:
}
err = json.Unmarshal(data, &opr)
if err != nil {
kv.log.Error("json Unmarshal sync data err:", zap.Error(err))
continue
}
switch opr.Op {
case SetOperateType:
kv.db.Set(opr.Key, string(opr.Value), -1)
case DeleteOperateType:
kv.db.Delete(opr.Key)
}
}
}()
return nil
}
func (kv *KeyValueDB) Get(key string) string {
val, ok := kv.db.Get(key)
if !ok {
return UnDefStr
}
return val.(string)
}
func (kv *KeyValueDB) Put(ctx context.Context, key, value string) error {
op := newOperation(key, []byte(value), SetOperateType)
_, err := kv.ev.Append(ctx, op.marshal())
if err != nil {
return err
}
kv.db.Set(key, value, -1)
return nil
}
func (kv *KeyValueDB) Delete(ctx context.Context, key string) error {
op := newOperation(key, nil, DeleteOperateType)
_, err := kv.ev.Append(ctx, op.marshal())
if err != nil {
return err
}
kv.db.Delete(key)
return nil
}
func (kv *KeyValueDB) List() map[string]string {
list := make(map[string]string)
for k, v := range kv.db.Items() {
list[k] = v.Object.(string)
}
return list
}
func (kv *KeyValueDB) Flush(ctx context.Context) error {
for k := range kv.db.Items() {
if err := kv.Delete(ctx, k); err != nil {
return err
}
kv.db.Delete(k)
}
return nil
}
func (kv *KeyValueDB) Close() {
kv.ev.Close()
}