-
Notifications
You must be signed in to change notification settings - Fork 0
/
state_machine.go
57 lines (50 loc) · 948 Bytes
/
state_machine.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
package raftgo
import (
"encoding/json"
"log"
"sync"
)
type Command struct {
Type string `json:"type"`
Key string `json:"key"`
Value string `json:"value,omitempty"`
}
type StateMachine interface {
Apply(command []byte)
}
type MemStateMachine struct {
state map[string]string
mu sync.RWMutex
}
func NewMemStateMachine() *MemStateMachine {
return &MemStateMachine{
state: make(map[string]string),
}
}
func (m *MemStateMachine) Get(key string) string {
m.mu.RLock()
defer m.mu.RUnlock()
value, ok := m.state[key]
if ok {
return value
}
return ""
}
func (m *MemStateMachine) Apply(command []byte) {
var cmd Command
err := json.Unmarshal(command, &cmd)
if err != nil {
log.Fatalf("Error unmarshalling command: %v", err)
}
log.Printf("%+v", cmd)
switch cmd.Type {
case "set":
m.mu.Lock()
m.state[cmd.Key] = cmd.Value
m.mu.Unlock()
case "rm":
m.mu.Lock()
delete(m.state, cmd.Key)
m.mu.Unlock()
}
}