main.rs 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. // select each connection and show log of traffic
  2. // use rpc to get some info from the ircd network
  3. // ircd::logger keeps track of network info
  4. // map rpc polls logger for info about nodes, etc
  5. use darkfi::{
  6. error::{Error, Result},
  7. rpc::{jsonrpc, jsonrpc::JsonResult},
  8. util::async_util,
  9. };
  10. use async_std::sync::{Arc, Mutex};
  11. use easy_parallel::Parallel;
  12. use log::debug;
  13. use serde_json::{json, Value};
  14. use smol::Executor;
  15. use std::{io, io::Read};
  16. use termion::{async_stdin, event::Key, input::TermRead, raw::IntoRawMode};
  17. use tui::{
  18. backend::{Backend, TermionBackend},
  19. Terminal,
  20. };
  21. use map::{node_info::NodeInfo, ui, App};
  22. struct Map {
  23. url: String,
  24. }
  25. impl Map {
  26. pub fn new(url: String) -> Self {
  27. Self { url }
  28. }
  29. async fn request(&self, r: jsonrpc::JsonRequest) -> Result<Value> {
  30. let reply: JsonResult = match jsonrpc::send_request(&self.url, json!(r)).await {
  31. Ok(v) => v,
  32. Err(e) => return Err(e),
  33. };
  34. match reply {
  35. JsonResult::Resp(r) => {
  36. debug!(target: "RPC", "<-- {}", serde_json::to_string(&r)?);
  37. Ok(r.result)
  38. }
  39. JsonResult::Err(e) => {
  40. debug!(target: "RPC", "<-- {}", serde_json::to_string(&e)?);
  41. Err(Error::JsonRpcError(e.error.message.to_string()))
  42. }
  43. JsonResult::Notif(n) => {
  44. debug!(target: "RPC", "<-- {}", serde_json::to_string(&n)?);
  45. Err(Error::JsonRpcError("Unexpected reply".to_string()))
  46. }
  47. }
  48. }
  49. // --> {"jsonrpc": "2.0", "method": "say_hello", "params": [], "id": 42}
  50. // <-- {"jsonrpc": "2.0", "result": "hello world", "id": 42}
  51. async fn _say_hello(&self) -> Result<Value> {
  52. let req = jsonrpc::request(json!("say_hello"), json!([]));
  53. Ok(self.request(req).await?)
  54. }
  55. //--> {"jsonrpc": "2.0", "method": "poll", "params": [], "id": 42}
  56. // <-- {"jsonrpc": "2.0", "result": {"nodeID": [], "nodeinfo" [], "id": 42}
  57. async fn get_info(&self) -> Result<Value> {
  58. let req = jsonrpc::request(json!("get_info"), json!([]));
  59. Ok(self.request(req).await?)
  60. }
  61. }
  62. #[async_std::main]
  63. async fn main() -> Result<()> {
  64. let stdout = io::stdout().into_raw_mode()?;
  65. let backend = TermionBackend::new(stdout);
  66. let mut terminal = Terminal::new(backend)?;
  67. terminal.clear()?;
  68. // let current_state = get_current_state.await;
  69. // let mut app = app.lock();
  70. // app.current_state = current_state;
  71. let app = Arc::new(Mutex::new(App::new()));
  72. //let app = App::new();
  73. let nthreads = num_cpus::get();
  74. let (signal, shutdown) = async_channel::unbounded::<()>();
  75. let ex = Arc::new(Executor::new());
  76. let ex2 = ex.clone();
  77. let (_, result) = Parallel::new()
  78. .each(0..nthreads, |_| smol::future::block_on(ex.run(shutdown.recv())))
  79. // Run the main future on the current thread.
  80. .finish(|| {
  81. smol::future::block_on(async move {
  82. start(ex2.clone(), app.lock().await.clone()).await?;
  83. run_app(&mut terminal, app.lock().await.clone()).await?;
  84. drop(signal);
  85. Ok::<(), darkfi::Error>(())
  86. })
  87. });
  88. result
  89. }
  90. async fn start(ex: Arc<Executor<'_>>, app: App) -> Result<()> {
  91. let client = Map::new("tcp://127.0.0.1:8000".to_string());
  92. ex.spawn(poll(client, app)).detach();
  93. Ok(())
  94. }
  95. async fn poll(client: Map, app: App) -> Result<()> {
  96. loop {
  97. let reply = client.get_info().await?;
  98. update(app.clone(), reply).await?;
  99. async_util::sleep(1).await;
  100. }
  101. }
  102. async fn update(app: App, reply: Value) -> Result<()> {
  103. if reply.as_object().is_some() && !reply.as_object().unwrap().is_empty() {
  104. //let args = params.as_array();
  105. let nodes = reply.as_object().unwrap().get("nodes").unwrap();
  106. let node1 = &nodes[0];
  107. let node2 = &nodes[1];
  108. let node3 = &nodes[2];
  109. let infos = vec![
  110. NodeInfo {
  111. id: node1["id"].to_string(),
  112. connections: node1["connections"].as_u64().unwrap() as usize,
  113. is_active: node2["is_active"].as_bool().unwrap(),
  114. last_message: node3["message"].to_string(),
  115. },
  116. //NodeInfo {
  117. // id: node2["id"].to_string(),
  118. // connections: node2["connections"].as_u64().unwrap() as usize,
  119. // is_active: node2["is_active"].as_bool().unwrap(),
  120. // last_message: node2["message"].to_string(),
  121. //},
  122. //NodeInfo {
  123. // id: node3["id"].to_string(),
  124. // connections: node3["connections"].as_u64().unwrap() as usize,
  125. // is_active: node3["is_active"].as_bool().unwrap(),
  126. // last_message: node3["message"].to_string(),
  127. //},
  128. ];
  129. //app.node_info(
  130. //let node_info = NodeInfoView::new(infos.clone());
  131. //let ids = vec![node1["id"].to_string(), node2["id"].to_string(), node3["id"].to_string()];
  132. // mutex
  133. app.update(infos).await;
  134. //let node_list = NodeIdList::new(ids);
  135. //println!("{}", test);
  136. // do something
  137. } else {
  138. // TODO: error handling
  139. println!("Reply is an error");
  140. }
  141. Ok(())
  142. }
  143. async fn run_app<B: Backend>(terminal: &mut Terminal<B>, mut app: App) -> io::Result<()> {
  144. let mut asi = async_stdin();
  145. terminal.clear()?;
  146. app.node_list.state.select(Some(0));
  147. app.node_info.index = 0;
  148. // acquire the mutex
  149. // let mut app = app.lock();
  150. loop {
  151. terminal.draw(|f| ui::ui(f, &mut app))?;
  152. for k in asi.by_ref().keys() {
  153. match k.unwrap() {
  154. Key::Char('q') => {
  155. terminal.clear()?;
  156. return Ok(())
  157. }
  158. Key::Char('j') => {
  159. app.node_list.next();
  160. app.node_info.next();
  161. }
  162. Key::Char('k') => {
  163. app.node_list.previous();
  164. app.node_info.previous();
  165. }
  166. _ => (),
  167. }
  168. }
  169. }
  170. }