-- Raft: leader election and log replication, every node a fibre on the -- simulated network (`docs/language/world.md`). -- -- Each node listens on its own address, dials every peer for its outbound -- messages, and reads each peer's inbound connection in a fibre of its own. -- Every reader, and a timer, sends into the node's one mailbox (a channel), and -- the node's main loop takes one event at a time from it: a peer's message or a -- tick. That loop is the whole of Raft's logic, and it never waits on anything -- but its mailbox. -- -- What a model needs to see is effects, so the program's state is where a real -- implementation keeps it: -- -- `Store` the persistent state — current term, vote, log — which Raft -- requires to survive a crash. Every write is a journalled -- operation, before the message it justifies is sent. -- `Machine` the state machine a committed entry is applied to, once, in -- index order. -- messages JSON, so a model reads `term`, `kind` and `entries` out of what -- one node sent another. use "std/net.nib" use "std/time.nib" use "std/random.nib" use "std/io.nib" data Entry where term :: Int; cmd :: String -- One record shape for every message: the kind says which fields mean -- something, and a model reads them all the same way. data Msg where kind :: String; term :: Int; from :: String; last_index :: Int; last_term :: Int; granted :: Bool; prev_index :: Int; prev_term :: Int; entries :: Vec; commit :: Int; success :: Bool; match_index :: Int data Ev where Tick; Got(Msg) -- A node's volatile state. `term`, `voted` and `log` are copies of what -- `Store` holds, kept beside the rest so one value is the node's whole view. data Node where me :: String; peers :: Vec; role :: String; term :: Int; voted :: String; log :: Vec; commit :: Int; applied :: Int; votes :: Vec; next :: Map; matched :: Map; deadline :: Int; beat :: Int; links :: Map -- What `Store` gives back to a node that starts: everything it saved. data Saved where term :: Int; voted :: String; log :: Vec interface Store where recover(node: String) -> Saved; save(node: String, term: Int, voted: String) -> (); append(node: String, keep: Int, entries: Vec) -> () -- Two rules this program can be built without, so a check of each has a -- known-wrong program to refuse. A node grants at most one vote per term -- (`one_vote`), and only to a candidate whose log is at least as up to date as -- its own (`check_log`). `Main` binds both as Raft states them; `Mutant` -- votes for every candidate that asks; `Careless` ignores the candidate's log. interface Rules where one_vote() -> Bool; check_log() -> Bool effector Strict is Rules where one_vote() = true check_log() = true effector Lax is Rules where one_vote() = false check_log() = true effector Blind is Rules where one_vote() = true check_log() = false interface Machine where apply(node: String, index: Int, cmd: String) -> (); applied(node: String) -> Vec -- An effector's cells outlive the node's fibres, so a crash loses none of -- what `Disk` holds: a node that starts again recovers it. effector Disk is Store where unkeyed var terms :: Map = {}; unkeyed var votes :: Map = {}; unkeyed var logs :: Map> = {}; recover(node) = Saved{ term: Map.get_or(terms, node, 0), voted: Map.get_or(votes, node, ""), log: Map.get_or(logs, node, #[]) } save(node, term, voted) = terms := Map.set(terms, node, term); votes := Map.set(votes, node, voted); () append(node, keep, entries) = logs := Map.set(logs, node, Vec.append(Vec.take(Map.get_or(logs, node, #[]), keep), entries)); () -- A store that writes as `Disk` does but recovers nothing, as a node that -- never syncs its writes would: after a crash it has forgotten its term and -- its vote. `Forgetful` binds it, so a check of durability has a program to -- refuse. effector Ram is Store where unkeyed var logs :: Map> = {}; recover(node) = Saved{ term: 0, voted: "", log: #[] } save(node, term, voted) = () append(node, keep, entries) = logs := Map.set(logs, node, Vec.append(Vec.take(Map.get_or(logs, node, #[]), keep), entries)); () -- A node that starts again applies its log from the first entry, so applying -- an index the machine already has changes nothing. effector Kv is Machine where unkeyed var done :: Map> = {}; apply(node, index, cmd) = let had = Map.get_or(done, node, #[]); if index == Vec.size(had) + 1 then (done := Map.set(done, node, Vec.push(had, cmd)); ()) else () applied(node) = Map.get_or(done, node, #[]) module Raft where -- ---- the cluster ------------------------------------------------------ func port :: -> Int = 7000 func hosts :: -> Vec = #["10.0.0.1", "10.0.0.2", "10.0.0.3"] func heartbeat_ms :: -> Int = 50 func max_log :: -> Int = 6 func run_ms :: -> Int = 3000 func tick_ms :: -> Int = 10 func others :: me: String -> Vec = Vec.filter(hosts()) { h -> h != me } func majority :: -> Int = Vec.size(hosts()) / 2 + 1 -- ---- reading a message ------------------------------------------------ func entries_of :: items, acc: Vec -> Vec raises Err.MissingField, Err.NotAnObject, Err.WrongType = match (items) [e, ...rest] => entries_of(rest, Vec.push(acc, Entry{ term: Json.int(e, "term"), cmd: Json.string(e, "cmd") })) [] => acc end -- A message from a peer is input: a field of the wrong shape is a -- `WrongType` the reader drops, as it drops a message that is not JSON. func decode :: text: String -> Msg raises Err.InvalidJson, Err.MissingField, Err.NotAnObject, Err.NotAList, Err.WrongType = let doc = Json.parse(text); Msg{ kind: Json.string(doc, "kind"), term: Json.int(doc, "term"), from: Json.string(doc, "from"), last_index: Json.int(doc, "last_index"), last_term: Json.int(doc, "last_term"), granted: Json.bool(doc, "granted"), prev_index: Json.int(doc, "prev_index"), prev_term: Json.int(doc, "prev_term"), entries: entries_of(Json.items(Json.field(doc, "entries")), #[]), commit: Json.int(doc, "commit"), success: Json.bool(doc, "success"), match_index: Json.int(doc, "match_index") } -- ---- messages ----------------------------------------------------------- func blank :: kind: String, term: Int, from: String -> Msg = Msg{ kind: kind, term: term, from: from, last_index: 0, last_term: 0, granted: false, prev_index: 0, prev_term: 0, entries: #[], commit: 0, success: false, match_index: 0 } func vote_req :: n: Node -> Msg = #{ blank("vote_req", n.term, n.me) with last_index: Vec.size(n.log), last_term: last_term(n.log) } func vote :: n: Node, granted: Bool -> Msg = #{ blank("vote", n.term, n.me) with granted: granted } func append_req :: n: Node, peer: String -> Msg = let prev = Map.get_or(n.next, peer, 1) - 1; #{ blank("append", n.term, n.me) with prev_index: prev, prev_term: term_at(n.log, prev), entries: Vec.drop(n.log, prev), commit: n.commit } func append_reply :: n: Node, ok: Bool, upto: Int -> Msg = #{ blank("append_ok", n.term, n.me) with success: ok, match_index: upto } -- ---- the log ------------------------------------------------------------- -- Index `i` is the log's `i`th entry, from 1; index 0 is before the log and -- has term 0. func term_at :: log: Vec, i: Int -> Int = if i <= 0 || i > Vec.size(log) then 0 else try Vec.get(log, i - 1).term rescue Err.IndexOutOfRange(_) => 0 end func last_term :: log: Vec -> Int = term_at(log, Vec.size(log)) -- The log after an `append` at `prev`: entries that agree with what is there -- are kept, and the first that disagrees cuts the rest. An empty `append` (a -- heartbeat) cuts nothing, which is Raft's rule and the easy one to break. func merge :: log: Vec, at: Int, incoming: Vec -> Vec = if Vec.size(incoming) == 0 then log else let head = try Vec.get(incoming, 0) rescue Err.IndexOutOfRange(_) => Entry{ term: 0, cmd: "" } end; if at < Vec.size(log) && term_at(log, at + 1) == head.term then merge(log, at + 1, Vec.drop(incoming, 1)) else Vec.append(Vec.take(log, at), incoming) -- ---- talking to peers ---------------------------------------------------- -- A lost message is Raft's ordinary case, so a send that fails is dropped. -- A connection that has closed (its peer crashed) is dialled again, once, -- on the next send to that peer, and a peer that does not answer is left -- without a link until a later send finds it back. func deliver :: conn: Handle, text: String -> Bool ! Net.Socket = try (let _ = @Net.Socket.send(conn, Bytes.from_string(text)); true) rescue Err.Closed(_) => false rescue HandleRefused(_) => false end func redial :: n: Node, peer: String -> Node ! Net.Socket = try #{ n with links: Map.set(n.links, peer, @Net.Socket.connect(peer, port())) } rescue Err.ConnectFailed(_) => #{ n with links: Map.remove(n.links, peer) } rescue Err.BindFailed(_) => #{ n with links: Map.remove(n.links, peer) } end func send :: n: Node, peer: String, m: Msg -> Node ! Net.Socket = let text = try Json.render(m) rescue Err.Unrenderable(_) => "" end; let linked = Map.has(n.links, peer); let ok = text != "" && linked && (try deliver(Map.get(n.links, peer), text) rescue Err.MissingField(_, _) => false end); if ok || text == "" then n else let r = redial(n, peer); let _ = if Map.has(r.links, peer) then (try deliver(Map.get(r.links, peer), text) rescue Err.MissingField(_, _) => false end) else false; r func broadcast :: n: Node, m: Msg -> Node ! Net.Socket = Vec.fold(n.peers, n, { acc, p -> send(acc, p, m) }) func replicate :: n: Node -> Node ! Net.Socket = Vec.fold(n.peers, n, { acc, p -> send(acc, p, append_req(acc, p)) }) -- ---- the rules ------------------------------------------------------------- func election_timeout :: -> Int ! Random.Source = 150 + (try @Random.Source.next_int(150) rescue Err.OutOfRange(_) => 0 end) -- A term newer than ours, from anyone, makes us a follower of it. func observe :: n: Node, term: Int -> Node ! Store = if term > n.term then let _ = @Store.save(n.me, term, ""); #{ n with role: "follower", term: term, voted: "", votes: #[] } else n func start_election :: n: Node, now: Int -> Node ! Store, Net.Socket, Random.Source = let term = n.term + 1; let _ = @Store.save(n.me, term, n.me); let c = #{ n with role: "candidate", term: term, voted: n.me, votes: #[n.me], deadline: now + election_timeout() }; broadcast(c, vote_req(c)) func become_leader :: n: Node, now: Int -> Node ! Net.Socket = let next = Vec.fold(n.peers, {}, { m, p -> Map.set(m, p, Vec.size(n.log) + 1) }); let matched = Vec.fold(n.peers, {}, { m, p -> Map.set(m, p, 0) }); replicate(#{ n with role: "leader", next: next, matched: matched, beat: now + heartbeat_ms() }) func up_to_date :: n: Node, m: Msg -> Bool = let mine = last_term(n.log); m.last_term > mine || (m.last_term == mine && m.last_index >= Vec.size(n.log)) func on_vote_req :: n: Node, m: Msg, now: Int -> Node ! Store, Net.Socket, Random.Source, Rules = let free = n.voted == "" || n.voted == m.from || !@Rules.one_vote(); let fresh = up_to_date(n, m) || !@Rules.check_log(); let grant = m.term == n.term && free && fresh; if grant then let _ = @Store.save(n.me, n.term, m.from); let g = #{ n with voted: m.from, deadline: now + election_timeout() }; send(g, m.from, vote(g, true)) else send(n, m.from, vote(n, false)) func on_vote :: n: Node, m: Msg, now: Int -> Node ! Net.Socket = if n.role == "candidate" && m.term == n.term && m.granted && Vec.find_index(n.votes) { v -> v == m.from } < 0 then let votes = Vec.push(n.votes, m.from); let c = #{ n with votes: votes }; if Vec.size(votes) >= majority() then become_leader(c, now) else c else n func on_append :: n: Node, m: Msg, now: Int -> Node ! Store, Net.Socket, Random.Source = if m.term < n.term then send(n, m.from, append_reply(n, false, 0)) else let f = #{ n with role: "follower", deadline: now + election_timeout() }; if m.prev_index > Vec.size(f.log) || term_at(f.log, m.prev_index) != m.prev_term then send(f, m.from, append_reply(f, false, 0)) else let log = merge(f.log, m.prev_index, m.entries); let _ = if Vec.size(m.entries) > 0 then @Store.append(f.me, Vec.size(log) - Vec.size(Vec.drop(log, m.prev_index)), Vec.drop(log, m.prev_index)) else (); let upto = m.prev_index + Vec.size(m.entries); let g = #{ f with log: log }; let h = if m.commit > g.commit then #{ g with commit: if m.commit < upto then m.commit else upto } else g; send(h, m.from, append_reply(h, true, upto)) -- The largest index a majority holds in the leader's own term, if it is past -- the commit point. func commit_from :: n: Node, i: Int -> Int = if i <= n.commit then n.commit else let holders = 1 + Vec.size(Vec.filter(n.peers) { p -> Map.get_or(n.matched, p, 0) >= i }); if holders >= majority() && term_at(n.log, i) == n.term then i else commit_from(n, i - 1) func on_append_ok :: n: Node, m: Msg -> Node ! Net.Socket = if n.role != "leader" || m.term != n.term then n else if m.success then let had = Map.get_or(n.matched, m.from, 0); let upto = if m.match_index > had then m.match_index else had; let p = #{ n with next: Map.set(n.next, m.from, upto + 1), matched: Map.set(n.matched, m.from, upto) }; #{ p with commit: commit_from(p, Vec.size(p.log)) } else let back = Map.get_or(n.next, m.from, 1) - 1; let p = #{ n with next: Map.set(n.next, m.from, if back < 1 then 1 else back) }; send(p, m.from, append_req(p, m.from)) -- Every committed entry not yet applied, in index order, once. func apply_committed :: n: Node -> Node ! Machine = if n.applied >= n.commit then n else let i = n.applied + 1; let cmd = try Vec.get(n.log, i - 1).cmd rescue Err.IndexOutOfRange(_) => "" end; let _ = @Machine.apply(n.me, i, cmd); apply_committed(#{ n with applied: i }) -- A leader proposes the next command on each heartbeat, until its log is full. func propose :: n: Node -> Node ! Store = if Vec.size(n.log) >= max_log() then n else let e = Entry{ term: n.term, cmd: "{n.me}/t{n.term}/{Vec.size(n.log) + 1}" }; let _ = @Store.append(n.me, Vec.size(n.log), #[e]); #{ n with log: Vec.push(n.log, e) } func on_tick :: n: Node, now: Int -> Node ! Store, Net.Socket, Random.Source = if n.role == "leader" then if now >= n.beat then let p = replicate(propose(n)); #{ p with beat: now + heartbeat_ms() } else n else if now >= n.deadline then start_election(n, now) else n func handle :: n: Node, ev: Ev, now: Int -> Node ! Store, Net.Socket, Random.Source, Machine, Rules = let next = match ev Tick => on_tick(n, now) Got(m) => let o = observe(n, m.term); if m.kind == "vote_req" then on_vote_req(o, m, now) else if m.kind == "vote" then on_vote(o, m, now) else if m.kind == "append" then on_append(o, m, now) else if m.kind == "append_ok" then on_append_ok(o, m) else o end; apply_committed(next) -- ---- the fibres of one node ---------------------------------------------- -- A tick every `tick_ms`, and one more at `stop`, so the loop wakes to see -- that the run is over rather than waiting on a mailbox nobody will fill. func timer :: mb: Channel, stop: Int -> () ! Time.Clock = let _ = @Time.Clock.sleep(tick_ms()); let sent = Channel.send(mb, Tick); if @Time.Clock.now() >= stop || !sent then () else timer(mb, stop) -- A reader ends with its connection: a peer that crashed dials again, and -- the acceptor gives that connection a reader of its own. func reader :: conn: Handle, mb: Channel, stop: Int -> () ! Net.Socket, Time.Clock = let bytes = try @Net.Socket.recv(conn) rescue Err.Closed(_) => Bytes.from_string("") rescue HandleRefused(_) => Bytes.from_string("") end; if @Time.Clock.now() >= stop || Bytes.length(bytes) == 0 then () else let sent = try Channel.send(mb, Got(decode(Bytes.to_string(bytes)))) rescue Err.InvalidJson(_) => true rescue Err.MissingField(_, _) => true rescue Err.NotAnObject(_) => true rescue Err.NotAList(_) => true rescue Err.WrongType(_) => true end; if sent then reader(conn, mb, stop) else () -- Every connection a peer opens gets a reader, for as long as the node runs: -- a peer that restarts opens new ones. func acceptor :: sw: Switch, mb: Channel, stop: Int -> () ! Net.Socket, Time.Clock = if @Time.Clock.now() >= stop then () else let _ = try let conn = @Net.Socket.accept(100); let _ = fork(sw) { -> reader(conn, mb, stop) }; () rescue Err.BindFailed(_) => () end; acceptor(sw, mb, stop) -- One try at each peer: a peer not listening yet is dialled again by the -- first send to it. func dial_all :: peers: Vec -> Map ! Net.Socket = Vec.fold(peers, {}, { links, p -> try Map.set(links, p, @Net.Socket.connect(p, port())) rescue Err.ConnectFailed(_) => links rescue Err.BindFailed(_) => links end }) func run_loop :: n: Node, mb: Channel, stop: Int -> Node ! Store, Net.Socket, Random.Source, Machine, Rules, Time.Clock raises Err.Closed, HandleRefused = let now = @Time.Clock.now(); if now >= stop then n else let ev = Channel.recv(mb); run_loop(handle(n, ev, @Time.Clock.now()), mb, stop) -- One life of a node: listen, recover what `Store` saved, and run until -- `stop`. A crash ends it from outside, killing every fibre it has. func node :: me: String, stop: Int -> () ! Store, Net.Socket, Random.Source, Machine, Rules, Time.Clock, Io.Print = try let _ = @Net.Socket.listen(me, port()); let saved = @Store.recover(me); let peers = others(me); Switch.run { sw -> let mb = Channel.make(sw); let _ = fork(sw) { -> acceptor(sw, mb, stop) }; let _ = fork(sw) { -> timer(mb, stop) }; let start = Node{ me: me, peers: peers, role: "follower", term: saved.term, voted: saved.voted, log: saved.log, commit: 0, applied: 0, votes: #[], next: {}, matched: {}, deadline: @Time.Clock.now() + election_timeout(), beat: 0, links: dial_all(peers) }; let fin = run_loop(start, mb, stop); let _ = Channel.close(mb); @Io.Print.println("{me}: {fin.role} in term {fin.term}, log {Vec.size(fin.log)}, commit {fin.commit}") } rescue Err.BindFailed(m) => @Io.Print.println("{me}: {m}") rescue Err.Closed(m) => @Io.Print.println("{me}: {m}") rescue HandleRefused(m) => @Io.Print.println("{me}: {m}") end -- A node's supervisor, outside the node: when a crash kills the node's -- fibres, the await is refused, and the supervisor starts the node again. -- Its `listen` waits until the world brings the host back. func keep :: me: String, stop: Int -> () ! Store, Net.Socket, Random.Source, Machine, Rules, Time.Clock, Io.Print = let crashed = try Switch.run { sw -> let _ = Fiber.await(fork(sw) { -> node(me, stop) }); false } rescue HandleRefused(_) => true end; if crashed && @Time.Clock.now() < stop then keep(me, stop) else () -- ---- the check at the end ------------------------------------------------- -- State machine safety, as the program can see it: every two nodes applied -- the same command at every index both reached. The model checks this of -- the journal; the program checks it of itself, so a run says so too. func agree :: a: Vec, b: Vec, i: Int -> Bool = if i >= Vec.size(a) || i >= Vec.size(b) then true else let same = try Vec.get(a, i) == Vec.get(b, i) rescue Err.IndexOutOfRange(_) => false end; if same then agree(a, b, i + 1) else false func consistent :: logs: Vec> -> Bool = Vec.all(logs) { a -> Vec.all(logs) { b -> agree(a, b, 0) } } func main :: -> String ! Store, Net.Socket, Random.Source, Machine, Rules, Time.Clock, Io.Print raises HandleRefused = let _ = Switch.run { sw -> let fs = Vec.map(hosts()) { h -> fork(sw) { -> keep(h, run_ms()) } }; Vec.fold(fs, (), { _, f -> Fiber.await(f) }) }; let logs = Vec.map(hosts()) { h -> @Machine.applied(h) }; let lens = Vec.fold(logs, "", { acc, l -> acc ++ " " ++ "{Vec.size(l)}" }); if consistent(logs) then "safe: applied{lens}" else "UNSAFE: the nodes applied different commands" wire Main runs Raft.main where Store = Disk, Machine = Kv, Rules = Strict, Net.Socket = Net.Sim, Time.Clock = Time.Sim, Random.Source = Random.Sim, Io.Print = Io.Stdout wire Careless runs Raft.main where Store = Disk, Machine = Kv, Rules = Blind, Net.Socket = Net.Sim, Time.Clock = Time.Sim, Random.Source = Random.Sim, Io.Print = Io.Stdout wire Mutant runs Raft.main where Store = Disk, Machine = Kv, Rules = Lax, Net.Socket = Net.Sim, Time.Clock = Time.Sim, Random.Source = Random.Sim, Io.Print = Io.Stdout wire Forgetful runs Raft.main where Store = Ram, Machine = Kv, Rules = Strict, Net.Socket = Net.Sim, Time.Clock = Time.Sim, Random.Source = Random.Sim, Io.Print = Io.Stdout