Last active
February 24, 2023 16:42
Gossip Glomers Challenge #3b: Multi-Node Broadcast
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
maelstrom "github.com/jepsen-io/maelstrom/demo/go" | |
"log" | |
"sync" | |
) | |
func main() { | |
n := maelstrom.NewNode() | |
var mu sync.Mutex | |
messageStore := make(map[any]struct{}) | |
var topology map[string]interface{} | |
n.Handle("broadcast", func(msg maelstrom.Message) error { | |
var body map[string]any | |
if err := json.Unmarshal(msg.Body, &body); err != nil { | |
return err | |
} | |
mu.Lock() | |
defer mu.Unlock() | |
if _, ok := messageStore[body["message"]]; ok { | |
return nil | |
} | |
messageStore[body["message"]] = struct{}{} | |
for node, neighbours := range topology { | |
if node == n.ID() { | |
for _, v := range neighbours.([]interface{}) { | |
n.Send(v.(string), body) | |
} | |
} | |
} | |
body = map[string]any{} | |
body["type"] = "broadcast_ok" | |
return n.Reply(msg, body) | |
}) | |
n.Handle("read", func(msg maelstrom.Message) error { | |
var body map[string]any | |
if err := json.Unmarshal(msg.Body, &body); err != nil { | |
return err | |
} | |
body = map[string]any{} | |
body["type"] = "read_ok" | |
var keys []any | |
mu.Lock() | |
for k := range messageStore { | |
keys = append(keys, k) | |
} | |
mu.Unlock() | |
body["messages"] = keys | |
return n.Reply(msg, body) | |
}) | |
n.Handle("topology", func(msg maelstrom.Message) error { | |
var body map[string]any | |
if err := json.Unmarshal(msg.Body, &body); err != nil { | |
return err | |
} | |
topology = body["topology"].(map[string]interface{}) | |
body = map[string]any{} | |
body["type"] = "topology_ok" | |
return n.Reply(msg, body) | |
}) | |
if err := n.Run(); err != nil { | |
log.Fatal(err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment