Skip to content

Instantly share code, notes, and snippets.

@bhargavrpatel
Last active December 11, 2018 03:08
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 bhargavrpatel/71db9d6d0133117f40f6d330a3f2bd75 to your computer and use it in GitHub Desktop.
Save bhargavrpatel/71db9d6d0133117f40f6d330a3f2bd75 to your computer and use it in GitHub Desktop.
# Use this to send commands
require "socket"
client = TCPSocket.new("0.0.0.0", 1234)
message = ARGV[0]
puts message
client << message
client.close
# ####################################################
#
# Raft node implementation
#
# References
# ----------
# https://raft.github.io/slides/raftuserstudy2013.pdf
#
# ####################################################
require "socket"
# Constants
ELECTION_TIMEOUT_RANGE = 150..300
# Enums
enum ElectionState
Leader
Candidate
Follower
end
class Node
def initialize(id : Int32, port : Int32)
@id = id
@port = port
@timeout = Random.rand(ELECTION_TIMEOUT_RANGE).as(Int32)
# Start communication channels
@channel = Channel(String|Nil).new
@state_channel = Channel(ElectionState).new
end
# Fiber - TCPServer
def start_listener
puts "Starting the TCP Server at: #{@port}"
server = TCPServer.new("0.0.0.0", @port)
loop do
server.accept do |client|
message = client.gets
@channel.send(message)
end
end
end
def start_election
puts "Starting Election Fiber..."
while true
item = @state_channel.receive
case item
when ElectionState::Follower
puts "[STATE] Now becoming a follower"
when ElectionState::Candidate
puts "[STATE] Now becoming a Candidate"
when ElectionState::Leader
puts "[STATE] Now becoming a Leader"
end
end
end
def run
spawn start_listener
spawn start_election
while true
select
when message = @channel.receive
case message
when "follower"
@state_channel.send(ElectionState::Follower)
when "candidate"
@state_channel.send(ElectionState::Candidate)
when "leader"
@state_channel.send(ElectionState::Leader)
when "exit"
break
else
# TODO: Do great things...
puts message
end
end
end
end
end
node = Node.new(1,1234)
node.run
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment