Skip to content

Instantly share code, notes, and snippets.

@avinassh

avinassh/3b.go Secret

Created February 26, 2023 10:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save avinassh/4acb68dbc15bebdef88b2637b8f91922 to your computer and use it in GitHub Desktop.
Save avinassh/4acb68dbc15bebdef88b2637b8f91922 to your computer and use it in GitHub Desktop.
no network parition
package main
import (
"encoding/json"
"log"
"os"
"sync"
maelstrom "github.com/jepsen-io/maelstrom/demo/go"
)
type State struct {
messages []int
nodeId string
nodeIds []string
*sync.Mutex
}
func NewState() *State {
return &State{
messages: make([]int, 0),
Mutex: &sync.Mutex{},
}
}
func (s *State) addMsg(msg int) {
s.Lock()
defer s.Unlock()
s.messages = append(s.messages, msg)
}
func (s *State) addTopo(nodes []string) {
s.Lock()
defer s.Unlock()
s.nodeIds = nodes
}
func main() {
l := log.New(os.Stderr, "", 0)
l.Prefix()
n := maelstrom.NewNode()
state := NewState()
n.Handle("broadcast", func(msg maelstrom.Message) error {
type broadcastMsg struct {
Type string `json:"type"`
Message int `json:"message,omitempty"`
}
var body broadcastMsg
if err := json.Unmarshal(msg.Body, &body); err != nil {
return err
}
state.addMsg(body.Message)
for _, id := range state.nodeIds {
if id == state.nodeId {
continue
}
if id == msg.Src {
continue
}
if err := n.Send(id, msg.Body); err != nil {
panic(err)
}
}
body.Message = 0
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["type"] = "read_ok"
body["messages"] = state.messages
return n.Reply(msg, body)
})
n.Handle("topology", func(msg maelstrom.Message) error {
type topologyMSG struct {
Type string `json:"type"`
Topology map[string][]string `json:"topology,omitempty"`
}
var body topologyMSG
if err := json.Unmarshal(msg.Body, &body); err != nil {
return err
}
// state.addTopo(getAllUniqueNodesFromTopology(state.nodeId, state.nodeIds, body.Topology))
state.addTopo(state.nodeIds)
body.Type = "topology_ok"
body.Topology = nil
return n.Reply(msg, body)
})
n.Handle("init", func(msg maelstrom.Message) error {
type initBody struct {
Type string `json:"type"`
MsgId int `json:"msg_id"`
NodeId string `json:"node_id"`
NodeIds []string `json:"node_ids"`
}
var body initBody
if err := json.Unmarshal(msg.Body, &body); err != nil {
return err
}
body.Type = "init_ok"
state.nodeId = body.NodeId
state.nodeIds = body.NodeIds
return n.Reply(msg, body)
})
if err := n.Run(); err != nil {
log.Printf("ERROR: %s", err)
os.Exit(1)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment