main.rs 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  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 app = Arc::new(Mutex::new(App::new()));
  69. let nthreads = num_cpus::get();
  70. let (signal, shutdown) = async_channel::unbounded::<()>();
  71. let ex = Arc::new(Executor::new());
  72. let ex2 = ex.clone();
  73. let (_, result) = Parallel::new()
  74. .each(0..nthreads, |_| smol::future::block_on(ex.run(shutdown.recv())))
  75. // Run the main future on the current thread.
  76. .finish(|| {
  77. smol::future::block_on(async move {
  78. listen(ex2.clone(), app.lock().await.clone()).await?;
  79. run_app(&mut terminal, app.lock().await.clone()).await?;
  80. drop(signal);
  81. Ok::<(), darkfi::Error>(())
  82. })
  83. });
  84. result
  85. }
  86. async fn listen(ex: Arc<Executor<'_>>, app: App) -> Result<()> {
  87. let client = Map::new("tcp://127.0.0.1:8000".to_string());
  88. ex.spawn(poll(client, app)).detach();
  89. Ok(())
  90. }
  91. async fn poll(client: Map, app: App) -> Result<()> {
  92. loop {
  93. let reply = client.get_info().await?;
  94. if reply.as_object().is_some() && !reply.as_object().unwrap().is_empty() {
  95. let nodes = reply.as_object().unwrap().get("nodes").unwrap();
  96. let node1 = &nodes[0];
  97. let node2 = &nodes[1];
  98. let node3 = &nodes[2];
  99. let infos = vec![
  100. NodeInfo {
  101. id: node1["id"].to_string(),
  102. connections: node1["connections"].as_u64().unwrap() as usize,
  103. is_active: node2["is_active"].as_bool().unwrap(),
  104. last_message: node3["message"].to_string(),
  105. },
  106. ];
  107. app.clone().update(infos).await;
  108. } else {
  109. // TODO: error handling
  110. println!("Reply is an error");
  111. }
  112. async_util::sleep(1).await;
  113. }
  114. }
  115. async fn run_app<B: Backend>(terminal: &mut Terminal<B>, mut app: App) -> io::Result<()> {
  116. let mut asi = async_stdin();
  117. terminal.clear()?;
  118. app.node_list.state.select(Some(0));
  119. app.node_info.index = 0;
  120. // acquire the mutex
  121. // let mut app = app.lock();
  122. loop {
  123. terminal.draw(|f| ui::ui(f, &mut app))?;
  124. for k in asi.by_ref().keys() {
  125. match k.unwrap() {
  126. Key::Char('q') => {
  127. terminal.clear()?;
  128. return Ok(())
  129. }
  130. Key::Char('j') => {
  131. app.node_list.next();
  132. app.node_info.next();
  133. }
  134. Key::Char('k') => {
  135. app.node_list.previous();
  136. app.node_info.previous();
  137. }
  138. _ => (),
  139. }
  140. }
  141. }
  142. }