-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
101 lines (91 loc) · 1.99 KB
/
server.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
package main
import (
"fmt"
"log"
"os"
"sync"
"time"
maelstrom "github.com/jepsen-io/maelstrom/demo/go"
)
const (
DEAD = iota
LEADER
FOLLOWER
CANDIDATE
)
type Server struct {
n *maelstrom.Node
mu sync.Mutex
db *Db
dbChan chan int
electionTimer *time.Timer
currentLeader string
State int
CurrentTerm int
VotedFor string
Log []LogEntry
CommitIndex int
LastApplied int
NextIndex map[string]int
MatchIndex map[string]int
}
func NewServer() *Server {
s := &Server{
n: maelstrom.NewNode(),
db: NewDb(),
dbChan: make(chan int, 10),
electionTimer: time.NewTimer(100 * time.Millisecond),
State: DEAD,
NextIndex: make(map[string]int),
MatchIndex: make(map[string]int),
}
// Make sure the log is never empty
s.Log = append(s.Log, LogEntry{
Index: 0,
Term: 0,
Command: map[string]any{
"type": "initialize",
},
})
return s
}
func (s *Server) Run() {
s.becomeFollower()
go func() {
for {
index := <-s.dbChan
s.mu.Lock()
command := s.Log[index].Command
if command["type"] == "write" {
fmt.Fprintln(os.Stderr, command)
_key := command["key"]
key := _key.(float64)
_val := command["val"]
val := _val.(float64)
if err := s.db.Set(int(key), int(val)); err != nil {
log.Fatalf("Error while writing to the db: %v\n", err)
}
} else if command["type"] == "cas" {
_key := command["key"]
key := _key.(float64)
_from := command["from"]
from := _from.(float64)
_to := command["to"]
to := _to.(float64)
_ = s.db.Cas(int(key), int(from), int(to))
} else if command["type"] == "initialize" {
} else {
log.Fatalf("Invalid command")
}
s.mu.Unlock()
}
}()
s.n.Handle("append_entries", s.appendEntriesHandler)
s.n.Handle("request_vote", s.requestVoteHandler)
s.n.Handle("read", s.handleRead)
s.n.Handle("write", s.handleWrite)
s.n.Handle("cas", s.handleCas)
if err := s.n.Run(); err != nil {
log.Fatal(err)
}
}