-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkvstore.go
102 lines (79 loc) · 1.88 KB
/
kvstore.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
package kv
import (
"context"
"errors"
"sync"
pb "github.com/SuhasHebbar/CS739-P2/proto"
)
const NON_EXISTENT_KEY_MSG = "key does not exist."
type KVStore struct {
store map[string]string
}
func (kv *KVStore) Get(key string) (string, error) {
val, hasKey := kv.store[key]
if hasKey {
return val, nil
} else {
return "", errors.New(NON_EXISTENT_KEY_MSG)
}
}
func (kv *KVStore) Set(key, value string) {
kv.store[key] = value
}
func (kv *KVStore) Delete(key string) error {
_, hasKey := kv.store[key]
if !hasKey {
return errors.New(NON_EXISTENT_KEY_MSG)
}
delete(kv.store, key)
return nil
}
func NewKVStore() *KVStore {
return &KVStore{
store: map[string]string{},
}
}
type SimpleKVRpcServer struct {
pb.UnimplementedRaftRpcServer
kv KVStore
lock sync.Mutex
}
func NewKVRpcServer() *SimpleKVRpcServer {
return &SimpleKVRpcServer{
kv: *NewKVStore(),
lock: sync.Mutex{},
}
}
func (kvs *SimpleKVRpcServer) Get(c context.Context, key *pb.Key) (*pb.Response, error) {
kvs.lock.Lock()
defer kvs.lock.Unlock()
val, err := kvs.kv.Get(key.Key)
response := &pb.Response{Response: val, Ok: true, IsLeader: true}
if err != nil {
response.Ok = false
response.Response = err.Error()
}
return response, nil
}
func (kvs *SimpleKVRpcServer) Set(c context.Context, keyValue *pb.KeyValuePair) (*pb.Response, error) {
kvs.lock.Lock()
defer kvs.lock.Unlock()
kvs.kv.Set(keyValue.Key, keyValue.Value)
response := &pb.Response{
Ok: true,
IsLeader: true,
}
return response, nil
}
// Return true if key existed previously and was removed, else return false.
func (kvs *SimpleKVRpcServer) Delete(c context.Context, key *pb.Key) (*pb.Response, error) {
kvs.lock.Lock()
defer kvs.lock.Unlock()
err := kvs.kv.Delete(key.Key)
response := &pb.Response{Ok: true, IsLeader: true}
if err != nil {
response.Ok = false
response.Response = err.Error()
}
return response, nil
}