-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandlers.go
139 lines (116 loc) · 2.47 KB
/
handlers.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
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
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"strconv"
"sync"
"time"
maelstrom "github.com/jepsen-io/maelstrom/demo/go"
)
type set struct {
h map[string]struct{}
}
// absorb is like union but does a set union in-place.
func (s *set) absorb(incoming set) {
for k := range incoming.h {
s.h[k] = struct{}{}
}
}
func (s *set) insert(ele string) {
s.h[ele] = struct{}{}
}
type nodeWrapper struct {
node *maelstrom.Node
setMu sync.RWMutex
set *set
initDone chan struct{}
}
func newNodeWrapper(node *maelstrom.Node) *nodeWrapper {
return &nodeWrapper{
node: node,
set: &set{h: make(map[string]struct{})},
initDone: make(chan struct{}),
}
}
func (n *nodeWrapper) initHandler(msg maelstrom.Message) error {
n.initDone <- struct{}{}
return nil
}
func (n *nodeWrapper) addSetHandler(msg maelstrom.Message) error {
n.node.Reply(msg, map[string]any{
"type": "add_ok",
})
var body map[string]any
if err := json.Unmarshal(msg.Body, &body); err != nil {
return err
}
element := body["element"]
n.setMu.Lock()
defer n.setMu.Unlock()
n.set.insert(fmt.Sprint(element))
return nil
}
func (n *nodeWrapper) readSetHandler(msg maelstrom.Message) error {
res := make([]any, 0, len(n.set.h))
n.setMu.RLock()
for ele := range n.set.h {
res = append(res, toInt(ele))
}
n.setMu.RUnlock()
return n.node.Reply(msg, map[string]any{
"type": "read_ok",
"value": res,
})
}
func (n *nodeWrapper) mergeHandler(msg maelstrom.Message) error {
var body mergeMessage
if err := json.Unmarshal(msg.Body, &body); err != nil {
return err
}
n.setMu.Lock()
defer n.setMu.Unlock()
log.Print("Before:", len(n.set.h))
n.set.absorb(set{body.Set})
log.Print("After:", len(n.set.h))
return nil
}
func (n *nodeWrapper) startAsyncReplication(ctx context.Context) {
// Wait for init message to come otherwise NodeIDs()
// will be empty and no replication will take place.
<-n.initDone
nodes := n.node.NodeIDs()
t := time.NewTicker(3 * time.Second)
defer t.Stop()
done := false
for {
select {
case <-t.C:
for _, node := range nodes {
// Don't replicate to self.
if node == n.node.ID() {
continue
}
n.setMu.RLock()
n.node.Send(node, map[string]any{
"type": "merge",
"set": n.set.h,
})
n.setMu.RUnlock()
}
case <-ctx.Done():
done = true
}
if done {
break
}
}
}
type mergeMessage struct {
Set map[string]struct{} `json:"set"`
}
func toInt(s string) int {
res, _ := strconv.Atoi(s)
return res
}