-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
94 lines (69 loc) · 1.48 KB
/
main.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
package main
import (
"encoding/json"
"log"
maelstrom "github.com/jepsen-io/maelstrom/demo/go"
)
type AddRequest struct {
maelstrom.MessageBody
Delta int `json:"delta"`
}
type PropagateRequest struct {
maelstrom.MessageBody
Count int `json:"count"`
}
type ReadResponse struct {
maelstrom.MessageBody
Value int `json:"value"`
}
var node = maelstrom.NewNode()
func main() {
crdt := NewCRDT()
count := 0
node.Handle("add", func(msg maelstrom.Message) error {
var body AddRequest
if err := json.Unmarshal(msg.Body, &body); err != nil {
return err
}
count += body.Delta
for _, neighbor := range node.NodeIDs() {
if neighbor == node.ID() {
continue
}
neighborMessage := PropagateRequest{
MessageBody: maelstrom.MessageBody{
Type: "propagate",
},
Count: count,
}
go func() {
node.Send(neighbor, neighborMessage)
}()
}
resBody := maelstrom.MessageBody{
Type: "add_ok",
}
return node.Reply(msg, resBody)
})
node.Handle("propagate", func(msg maelstrom.Message) error {
var body PropagateRequest
if err := json.Unmarshal(msg.Body, &body); err != nil {
return err
}
crdt.Sync(msg.Src, body.Count)
return nil
})
node.Handle("read", func(msg maelstrom.Message) error {
value := count + crdt.Read()
resBody := ReadResponse{
MessageBody: maelstrom.MessageBody{
Type: "read_ok",
},
Value: value,
}
return node.Reply(msg, resBody)
})
if err := node.Run(); err != nil {
log.Fatal(err)
}
}