-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
287 lines (228 loc) · 5.79 KB
/
main.go
File metadata and controls
287 lines (228 loc) · 5.79 KB
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
package main
import (
"context"
"encoding/json"
"log"
"maps"
"math/rand/v2"
"os"
"os/signal"
"sync"
"time"
maelstrom "github.com/jepsen-io/maelstrom/demo/go"
)
func main() {
rootCtx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
defer stop()
storage := newMessagesStorage()
n := maelstrom.NewNode()
ns := newNodeServer(n, storage)
n.Handle("broadcast", ns.handleBroadcast)
n.Handle("read", ns.handleRead)
n.Handle("topology", ns.handleTopology)
n.Handle("sync_state", ns.handleSyncState)
stateSync := newStateSyncronizer(n, storage, 3*time.Second)
go stateSync.run(rootCtx)
go func() {
if err := n.Run(); err != nil {
log.Fatal(err)
}
}()
<-rootCtx.Done()
}
type nodeServer struct {
node *maelstrom.Node
storage *messagesStorage
}
func newNodeServer(n *maelstrom.Node, storage *messagesStorage) *nodeServer {
return &nodeServer{
node: n,
storage: storage,
}
}
func (ns *nodeServer) handleRead(msg maelstrom.Message) error {
return ns.node.Reply(msg, map[string]any{
"type": "read_ok",
"messages": ns.storage.getMessages(),
})
}
func (ns *nodeServer) handleBroadcast(msg maelstrom.Message) error {
body := struct {
Message int `json:"message"`
MsgID int `json:"msg_id"`
ForwardNode string `json:"forward_node"`
}{}
if err := json.Unmarshal(msg.Body, &body); err != nil {
return err
}
// Save the message to the node's state
isDuplicateMsg := ns.storage.addMessage(body.Message)
if isDuplicateMsg {
if body.MsgID == 0 {
// Do not reply to fire-and-forget messages
return nil
}
// Skip broadcasting the message if it has been seen before
return ns.node.Reply(msg, map[string]any{
"type": "broadcast_ok",
})
}
neighbors := ns.node.NodeIDs()
var forwardNode string
if body.MsgID != 0 {
// Select additional node as a "backup" so this node will forward the message again to all other nodes
forwardNode = pickRandomNode(ns.node.ID(), neighbors)
} else {
// Check if current node is a backup node, if not - we don't need to forward the message further
if ns.node.ID() != forwardNode {
return nil
}
}
wg := sync.WaitGroup{}
wg.Add(len(neighbors))
// Broadcast message to all node's neighbors
for _, neighbor := range neighbors {
if neighbor == ns.node.ID() || neighbor == msg.Src {
wg.Done()
// Skip sending the message to the node itself and the sender
continue
}
go func() {
defer wg.Done()
// Retry sending the message until it is successful
for {
if err := ns.node.Send(neighbor, map[string]any{
"type": "broadcast",
"message": body.Message,
"forward_node": forwardNode,
}); err == nil {
break
}
}
}()
}
wg.Wait()
if body.MsgID == 0 {
// Do not reply to fire-and-forget messages
return nil
}
return ns.node.Reply(msg, map[string]any{
"type": "broadcast_ok",
})
}
func pickRandomNode(currentPrimary string, nodes []string) string {
rand.Shuffle(len(nodes), func(i, j int) {
nodes[i], nodes[j] = nodes[j], nodes[i]
})
if len(nodes) > 1 && nodes[0] == currentPrimary {
return nodes[1]
}
return nodes[0]
}
func (ns *nodeServer) handleTopology(msg maelstrom.Message) error {
return ns.node.Reply(msg, map[string]any{
"type": "topology_ok",
})
}
func (ns *nodeServer) handleSyncState(msg maelstrom.Message) error {
body := struct {
Messages []int `json:"messages"`
}{}
if err := json.Unmarshal(msg.Body, &body); err != nil {
return err
}
ns.storage.mergeMessages(body.Messages)
return nil
}
/* State syncronizer */
type stateSyncronizer struct {
node *maelstrom.Node
interval time.Duration
storage *messagesStorage
lastSyncMap map[int]struct{}
}
func newStateSyncronizer(n *maelstrom.Node, storage *messagesStorage, interval time.Duration) *stateSyncronizer {
return &stateSyncronizer{
node: n,
interval: interval,
storage: storage,
lastSyncMap: make(map[int]struct{}, 0),
}
}
func (ss *stateSyncronizer) run(ctx context.Context) {
ticker := time.NewTicker(ss.interval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
ss.syncState()
ticker.Reset(ss.interval)
}
}
}
func (ss *stateSyncronizer) syncState() {
messages := ss.storage.getMessages()
// Skip syncing if the state has not changed
currentMessages := make(map[int]struct{}, len(messages))
for _, msg := range messages {
currentMessages[msg] = struct{}{}
}
if maps.Equal(currentMessages, ss.lastSyncMap) {
return
}
// Send current node state to all neighbors
for _, node := range ss.node.NodeIDs() {
if node == ss.node.ID() {
// Skip sending the message to the node itself
continue
}
go func() {
if _, err := ss.node.SyncRPC(context.Background(), node, map[string]any{
"type": "sync_state",
"messages": messages,
}); err != nil {
// For now we just skip error handling and retries
return
}
}()
}
// Update the last synced state
ss.lastSyncMap = currentMessages
}
/* Messages storage */
type messagesStorage struct {
messagesMu sync.RWMutex
messages map[int]struct{}
}
func newMessagesStorage() *messagesStorage {
return &messagesStorage{
messages: make(map[int]struct{}, 0),
}
}
func (ms *messagesStorage) addMessage(msg int) (duplicate bool) {
ms.messagesMu.Lock()
defer ms.messagesMu.Unlock()
_, duplicate = ms.messages[msg]
if !duplicate {
ms.messages[msg] = struct{}{}
}
return duplicate
}
func (ms *messagesStorage) getMessages() []int {
ms.messagesMu.RLock()
defer ms.messagesMu.RUnlock()
msgs := make([]int, 0, len(ms.messages))
for k := range ms.messages {
msgs = append(msgs, k)
}
return msgs
}
func (ms *messagesStorage) mergeMessages(newMessages []int) {
ms.messagesMu.Lock()
defer ms.messagesMu.Unlock()
for _, msg := range newMessages {
ms.messages[msg] = struct{}{}
}
}