-
Notifications
You must be signed in to change notification settings - Fork 2
/
counter.go
128 lines (102 loc) · 2.12 KB
/
counter.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
package main
import (
"context"
"encoding/json"
"log"
"os"
"sync"
"gossip-glomers/internal/model"
maelstrom "github.com/jepsen-io/maelstrom/demo/go"
)
const (
key = "key"
)
type Counter struct {
value int
mu sync.Mutex
current int
}
func main() {
n := maelstrom.NewNode()
kv := maelstrom.NewSeqKV(n)
counter := &Counter{value: 0}
n.Handle("add", func(msg maelstrom.Message) error {
var body map[string]any
if err := json.Unmarshal(msg.Body, &body); err != nil {
return err
}
m := body["delta"]
v := int(m.(float64))
counter.mu.Lock()
for {
val, err0 := kv.Read(context.Background(), key)
if err0 != nil {
val = 0
}
fn := val.(int) + v
err := kv.CompareAndSwap(context.Background(), key, val, fn, true)
if err == nil {
counter.value = fn
break
}
}
go func() {
body["type"] = "sync"
body["new-val"] = counter.value
for _, next := range n.NodeIDs() {
dst := next
go func() {
for {
_, err := n.SyncRPC(context.Background(), dst, body)
if err == nil {
break
}
}
}()
}
}()
counter.mu.Unlock()
rsp := &model.SimpleResp{Type: "add_ok"}
return n.Reply(msg, rsp)
})
n.Handle("sync", func(msg maelstrom.Message) error {
var body map[string]any
if err := json.Unmarshal(msg.Body, &body); err != nil {
return err
}
m := body["new-val"]
v := int(m.(float64))
counter.mu.Lock()
if counter.value < v {
counter.value = v
}
counter.mu.Unlock()
rsp := &model.SimpleResp{Type: "sync_ok"}
return n.Reply(msg, rsp)
})
n.Handle("read", func(msg maelstrom.Message) error {
var body map[string]any
if err := json.Unmarshal(msg.Body, &body); err != nil {
return err
}
counter.mu.Lock()
val, err := kv.Read(context.Background(), key)
if err != nil {
body["value"] = 0
} else {
body["value"] = val
if val.(int) > counter.value {
body["value"] = val
} else {
body["value"] = counter.value
}
}
counter.mu.Unlock()
body["type"] = "read_ok"
return n.Reply(msg, body)
})
if err := n.Run(); err != nil {
log.Printf("ERROR: %s", err)
os.Exit(1)
}
}