-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
101 lines (74 loc) · 1.76 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
95
96
97
98
99
100
101
package main
import (
"encoding/json"
"fmt"
"gossip-gloomers/utils"
"os"
"time"
"log"
maelstrom "github.com/jepsen-io/maelstrom/demo/go"
)
type BroadcastRequest struct {
maelstrom.MessageBody
Message int `json:"message"`
}
type TopologyRequest struct {
maelstrom.MessageBody
Topology map[string][]string `json:"topology"`
}
type GossipRequest struct {
maelstrom.MessageBody
Messages []int `json:"messages"`
}
type ReadResponse struct {
maelstrom.MessageBody
Messages []int `json:"messages"`
}
var node = maelstrom.NewNode()
var broadcastInterval = 1500 * time.Millisecond // 1.5s
func main() {
set := utils.NewSet[int]()
broadcast := NewBroadcaster(node, set, broadcastInterval)
node.Handle("broadcast", func(msg maelstrom.Message) error {
var body BroadcastRequest
if err := json.Unmarshal(msg.Body, &body); err != nil {
return err
}
resBody := maelstrom.MessageBody{
Type: "broadcast_ok",
}
set.Add(body.Message)
broadcast.Append(body.Message)
return node.Reply(msg, resBody)
})
node.Handle("gossip", func(msg maelstrom.Message) error {
var body GossipRequest
if err := json.Unmarshal(msg.Body, &body); err != nil {
return err
}
set.AddAll(body.Messages)
return nil
})
node.Handle("read", func(msg maelstrom.Message) error {
msgs := set.GetAll()
resBody := ReadResponse{
MessageBody: maelstrom.MessageBody{
Type: "read_ok",
},
Messages: msgs,
}
return node.Reply(msg, resBody)
})
node.Handle("topology", func(msg maelstrom.Message) error {
resBody := maelstrom.MessageBody{
Type: "topology_ok",
}
return node.Reply(msg, resBody)
})
go broadcast.Start()
defer broadcast.Stop()
if err := node.Run(); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
log.Fatal(err)
}
}