-
Notifications
You must be signed in to change notification settings - Fork 0
/
store.go
99 lines (87 loc) · 1.63 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
package raft
import (
"encoding/json"
"fmt"
"io"
"sync"
"github.com/hashicorp/raft"
)
type Store struct {
mu sync.RWMutex
kv map[string]string
}
func (s *Store) Apply(l *raft.Log) interface{} {
var c Command
if err := json.Unmarshal(l.Data, &c); err != nil {
panic(fmt.Sprintf("failed to unmarshal command: %s", err.Error()))
}
switch c.Op {
case Set:
s.Set(c.Key, c.Value)
return nil
case Delete:
s.Delete(c.Key)
return nil
default:
panic(fmt.Sprintf("unrecognized command op: %s", c.Op))
}
}
func (s *Store) Restore(rc io.ReadCloser) error {
o := make(map[string]string)
if err := json.NewDecoder(rc).Decode(&o); err != nil {
return err
}
s.kv = o
return nil
}
func (s *Store) Snapshot() (raft.FSMSnapshot, error) {
s.mu.Lock()
defer s.mu.Unlock()
o := make(map[string]string)
for k, v := range s.kv {
o[k] = v
}
return &snapshot{store: o}, nil
}
func (s *Store) Get(key string) (string, bool) {
s.mu.RLock()
defer s.mu.RUnlock()
if val, ok := s.kv[key]; ok {
return val, ok
}
return "", false
}
func (s *Store) Set(key, value string) {
s.mu.Lock()
s.kv[key] = value
s.mu.Unlock()
}
func (s *Store) Delete(key string) {
s.mu.Lock()
delete(s.kv, key)
s.mu.Unlock()
}
type snapshot struct {
store map[string]string
}
func (s *snapshot) Persist(sink raft.SnapshotSink) error {
err := func() error {
b, err := json.Marshal(s.store)
if err != nil {
return err
}
if _, err := sink.Write(b); err != nil {
return err
}
if err := sink.Close(); err != nil {
return err
}
return nil
}()
if err != nil {
sink.Cancel()
return err
}
return nil
}
func (s *snapshot) Release() {}