1
0

terrible code and echo_ok complete

This commit is contained in:
Ishan Jain 2024-01-03 03:31:13 +05:30
parent 15167131f9
commit 74107a9c68
Signed by: ishan
GPG Key ID: 0506DB2A1CC75C27
3 changed files with 109 additions and 24 deletions

View File

@ -1,25 +1,83 @@
use std::io::{stdin, stdout, Stdin, Stdout}; pub mod types;
use crate::types::Message;
use std::{
collections::HashMap,
io::{stdin, stdout, BufRead, BufReader, Error as IoError, Stdin, Stdout, Write},
rc::Rc,
sync::{Arc, Mutex},
};
pub struct Malestorm { pub struct Malestorm<'a> {
stdin: Stdin, stdin: Stdin,
stdout: Stdout, pub stdout: Stdout,
pub handlers: HashMap<&'a str, Box<dyn Fn(Message)>>,
} }
impl Default for Malestorm { impl<'a> Default for Malestorm<'a> {
fn default() -> Self { fn default() -> Self {
Self { Self {
stdin: stdin(), stdin: stdin(),
stdout: stdout(), stdout: stdout(),
handlers: HashMap::new(),
} }
} }
} }
impl Malestorm { impl<'a> Malestorm<'a> {
pub fn run(self) { pub fn run(self) {
loop {} let mut reader = BufReader::new(self.stdin);
let mut buf = String::new();
loop {
let read = match reader.read_line(&mut buf) {
Ok(v) => v,
Err(e) => panic!("{:?}", e),
};
if read == 0 {
continue;
}
let message: Message = match serde_json::from_str(&buf) {
Ok(v) => v,
Err(e) => {
eprintln!("error in parsing input: {:?}", e);
continue;
}
};
let mtype = message.body.message_type.clone();
let handler = match self.handlers.get(&mtype.as_str()) {
Some(v) => v,
None => {
eprintln!("no handler found for {}", message.body.message_type);
continue;
}
};
handler(message);
}
} }
fn read() {} pub fn register(&mut self, name: &'a str, func: impl Fn(Message) + 'a + 'static) {
self.handlers
.insert(name, Box::new(move |msg: Message| func(msg)));
}
fn write() {} pub fn send(&self, msg: Message) -> Result<(), IoError> {
let out = serde_json::to_vec(&msg)?;
match self.write(&out) {
Ok(_) => Ok(()),
Err(e) => Err(e),
}
}
fn write(&self, buf: &[u8]) -> Result<usize, IoError> {
let mut writer = self.stdout.lock();
writer.write(buf)
}
} }

View File

@ -1,10 +1,44 @@
#![allow(special_module_name)] #![allow(special_module_name)]
mod lib; use std::{
mod types; io::{stdout, Write},
rc::Rc,
sync::{Arc, Mutex},
};
use crate::lib::Malestorm; use distributed_systems_flyio::{
types::{EchoMessage, Message, MessageBody},
Malestorm,
};
fn main() { fn main() {
let program = Malestorm::default(); let mut program = Malestorm::default();
let stdout = Arc::new(stdout());
let handlers = &mut program.handlers;
handlers.insert(
"echo",
Box::new(move |mut msg: Message| {
let message_body: EchoMessage = serde_json::from_value(msg.body.message_body)
.expect("error in parsing message body");
msg.body.message_type = "echo_ok".into();
msg.body.message_body = serde_json::to_value(message_body).unwrap();
match serde_json::to_vec(&msg).map(|buf| {
let mut writer = stdout.lock();
writer.write_all(&buf).expect("error in writing content");
writer.flush()
}) {
Ok(_) => (),
Err(e) => {
eprintln!("error in writing response: {}", e);
}
};
}),
);
program.run();
} }

View File

@ -9,21 +9,15 @@ pub struct Message {
} }
#[derive(Debug, Serialize, Deserialize)] #[derive(Debug, Serialize, Deserialize)]
pub(crate) struct MessageBody { pub struct MessageBody {
msg_id: Option<i64>, pub msg_id: Option<i64>,
in_reply_to: Option<i64>, pub in_reply_to: Option<i64>,
#[serde(rename = "type")] #[serde(rename = "type")]
message_type: String, pub message_type: String,
#[serde(flatten)] #[serde(flatten)]
pub message_body: MessageEnum, pub message_body: serde_json::Value,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged, deny_unknown_fields)]
pub enum MessageEnum {
Echo(EchoMessage),
} }
#[derive(Debug, Serialize, Deserialize)] #[derive(Debug, Serialize, Deserialize)]
@ -37,7 +31,6 @@ mod test {
use super::*; use super::*;
#[test]
pub fn extraneous_fields_fail() { pub fn extraneous_fields_fail() {
let body = "{ let body = "{
\"src\": \"c1\", \"src\": \"c1\",