passes global counter

This commit is contained in:
Joe Ardent 2024-06-04 12:58:38 -07:00
parent 95588c0dad
commit 4c89bf7a5c

View file

@ -3,10 +3,10 @@ use nebkor_maelstrom::{kv::Kv, mk_payload, Body, Message, Node, Runner};
const KEY: &str = "COUNTER"; const KEY: &str = "COUNTER";
#[derive(Clone, Default)] #[derive(Clone, Default)]
struct Counter; struct Counter(i64);
fn main() { fn main() {
let node = Counter; let node = Counter(0);
let runner = Runner::new(node); let runner = Runner::new(node);
@ -20,6 +20,14 @@ fn main() {
runner.run(Some(on_init)); runner.run(Some(on_init));
} }
fn gossip(neighbors: &[&String], runner: &Runner, val: i64) {
let payload = mk_payload(&[("goss", val.into())]);
let body = Body::from_type("gossip").with_payload(payload);
for node in neighbors {
runner.send(node, body.clone());
}
}
impl Node for Counter { impl Node for Counter {
fn handle(&mut self, runner: &Runner, req: Message) { fn handle(&mut self, runner: &Runner, req: Message) {
let typ = req.body.typ.as_str(); let typ = req.body.typ.as_str();
@ -28,19 +36,38 @@ impl Node for Counter {
"add" => { "add" => {
let delta = req.body.payload.get("delta").unwrap().as_i64().unwrap(); let delta = req.body.payload.get("delta").unwrap().as_i64().unwrap();
loop { loop {
let cur = kv.read(runner, KEY).unwrap().unwrap().as_i64().unwrap(); let cur = self.0;
match kv.cas(runner, KEY, cur.into(), (cur + delta).into(), false) { let new = cur + delta;
Err(_) => {} match kv.cas(runner, KEY, cur.into(), new.into(), false) {
Ok(_) => break, Err(_e) => {
let cur = kv.read(runner, KEY).unwrap().unwrap().as_i64().unwrap();
self.0 = cur;
}
Ok(_) => {
let nodes = runner
.nodes()
.iter()
.filter(|e| e != &&runner.node_id())
.collect::<Vec<_>>();
self.0 = new;
gossip(&nodes, runner, new);
break;
}
} }
} }
runner.reply(&req, Body::from_type("add_ok")); runner.reply(&req, Body::from_type("add_ok"));
} }
"read" => { "read" => {
let val = kv.read(runner, KEY).unwrap().unwrap(); let val = self.0;
let body = Body::from_type("read_ok").with_payload(mk_payload(&[("value", val)])); let body =
Body::from_type("read_ok").with_payload(mk_payload(&[("value", val.into())]));
runner.reply(&req, body); runner.reply(&req, body);
} }
"gossip" => {
let val = req.body.payload.get("goss").unwrap().as_i64().unwrap();
self.0 = val.max(self.0);
}
_ => { _ => {
eprintln!("unknown type: {req:?}"); eprintln!("unknown type: {req:?}");
} }