-
-
Save bhargavrpatel/71db9d6d0133117f40f6d330a3f2bd75 to your computer and use it in GitHub Desktop.
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
# Use this to send commands | |
require "socket" | |
client = TCPSocket.new("0.0.0.0", 1234) | |
message = ARGV[0] | |
puts message | |
client << message | |
client.close |
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
# #################################################### | |
# | |
# 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