main.rs 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. use darkfi::{
  2. cli::{
  3. cli_config::{log_config, spawn_config},
  4. Config, MapConfig,
  5. },
  6. error::{Error, Result},
  7. rpc::{jsonrpc, jsonrpc::JsonResult},
  8. util::{async_util, join_config_path},
  9. };
  10. use async_std::sync::Arc;
  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, path::PathBuf};
  16. use termion::{async_stdin, event::Key, input::TermRead, raw::IntoRawMode};
  17. use tui::{
  18. backend::{Backend, TermionBackend},
  19. Terminal,
  20. };
  21. use map::{
  22. model::{IdList, InfoList, NodeInfo},
  23. ui,
  24. view::{IdListView, InfoListView},
  25. Model, View,
  26. };
  27. const CONFIG_FILE_CONTENTS: &[u8] = include_bytes!("../map_config.toml");
  28. struct Map {
  29. url: String,
  30. }
  31. impl Map {
  32. pub fn new(url: String) -> Self {
  33. Self { url }
  34. }
  35. async fn request(&self, r: jsonrpc::JsonRequest) -> Result<Value> {
  36. let reply: JsonResult = match jsonrpc::send_request(&self.url, json!(r)).await {
  37. Ok(v) => v,
  38. Err(e) => return Err(e),
  39. };
  40. match reply {
  41. JsonResult::Resp(r) => {
  42. debug!(target: "RPC", "<-- {}", serde_json::to_string(&r)?);
  43. Ok(r.result)
  44. }
  45. JsonResult::Err(e) => {
  46. debug!(target: "RPC", "<-- {}", serde_json::to_string(&e)?);
  47. Err(Error::JsonRpcError(e.error.message.to_string()))
  48. }
  49. JsonResult::Notif(n) => {
  50. debug!(target: "RPC", "<-- {}", serde_json::to_string(&n)?);
  51. Err(Error::JsonRpcError("Unexpected reply".to_string()))
  52. }
  53. }
  54. }
  55. // --> {"jsonrpc": "2.0", "method": "say_hello", "params": [], "id": 42}
  56. // <-- {"jsonrpc": "2.0", "result": "hello world", "id": 42}
  57. async fn _say_hello(&self) -> Result<Value> {
  58. let req = jsonrpc::request(json!("say_hello"), json!([]));
  59. Ok(self.request(req).await?)
  60. }
  61. //--> {"jsonrpc": "2.0", "method": "poll", "params": [], "id": 42}
  62. // <-- {"jsonrpc": "2.0", "result": {"nodeID": [], "nodeinfo" [], "id": 42}
  63. async fn get_info(&self) -> Result<Value> {
  64. let req = jsonrpc::request(json!("get_info"), json!([]));
  65. Ok(self.request(req).await?)
  66. }
  67. }
  68. #[async_std::main]
  69. async fn main() -> Result<()> {
  70. let config_path = join_config_path(&PathBuf::from("map_config.toml"))?;
  71. // Spawn config file if it's not in place already.
  72. spawn_config(&config_path, CONFIG_FILE_CONTENTS)?;
  73. let config = Config::<MapConfig>::load(config_path)?;
  74. let stdout = io::stdout().into_raw_mode()?;
  75. let backend = TermionBackend::new(stdout);
  76. let mut terminal = Terminal::new(backend)?;
  77. terminal.clear()?;
  78. let infos = vec![NodeInfo::new()];
  79. //let infos = vec![
  80. // NodeInfo {
  81. // id: "0385048034sodisofjhosd1111q3434".to_string(),
  82. // connections: 10,
  83. // is_active: true,
  84. // last_message: "hey how are you?".to_string(),
  85. // },
  86. // NodeInfo {
  87. // id: "09w30we9wsnfksdfkdjflsjkdfjdfsd".to_string(),
  88. // connections: 5,
  89. // is_active: false,
  90. // last_message: "lmao".to_string(),
  91. // },
  92. // NodeInfo {
  93. // id: "038043325alsdlasjfrsdfsdfsdjsdf".to_string(),
  94. // connections: 7,
  95. // is_active: true,
  96. // last_message: "gm".to_string(),
  97. // },
  98. // NodeInfo {
  99. // id: "04985034953ldflsdjflsdjflsdjfii".to_string(),
  100. // connections: 2,
  101. // is_active: true,
  102. // last_message: "hihi".to_string(),
  103. // },
  104. // NodeInfo {
  105. // id: "09850249352asdjapsdikalskasdkas".to_string(),
  106. // connections: 10,
  107. // is_active: true,
  108. // last_message: "wtf".to_string(),
  109. // },
  110. //];
  111. let info_list = InfoList::new(infos.clone());
  112. let ids = vec![String::new()];
  113. let id_list = IdList::new(ids);
  114. let model = Arc::new(Model::new(id_list, info_list));
  115. //let model = Model::new(id_list, info_list);
  116. let nthreads = num_cpus::get();
  117. let (signal, shutdown) = async_channel::unbounded::<()>();
  118. let ex = Arc::new(Executor::new());
  119. let ex2 = ex.clone();
  120. let (_, result) = Parallel::new()
  121. .each(0..nthreads, |_| smol::future::block_on(ex.run(shutdown.recv())))
  122. // Run the main future on the current thread.
  123. .finish(|| {
  124. smol::future::block_on(async move {
  125. run_rpc(&config, ex2.clone(), model.clone()).await?;
  126. render(&mut terminal, model.clone()).await?;
  127. drop(signal);
  128. Ok::<(), darkfi::Error>(())
  129. })
  130. });
  131. result
  132. }
  133. async fn run_rpc(config: &MapConfig, ex: Arc<Executor<'_>>, model: Arc<Model>) -> Result<()> {
  134. // TODO: listen to multiple nodes
  135. let client = Map::new(config.nodes[0].node_id.to_string());
  136. ex.spawn(poll(client, model)).detach();
  137. Ok(())
  138. }
  139. async fn poll(client: Map, model: Arc<Model>) -> Result<()> {
  140. loop {
  141. let reply = client.get_info().await?;
  142. if reply.as_object().is_some() && !reply.as_object().unwrap().is_empty() {
  143. let nodes = reply.as_object().unwrap().get("nodes").unwrap();
  144. // TODO: generalize this
  145. let node1 = &nodes[0];
  146. let node2 = &nodes[1];
  147. let node3 = &nodes[2];
  148. // TODO: error handling
  149. let infos = vec![
  150. NodeInfo {
  151. id: node1["id"].to_string(),
  152. connections: node1["connections"].as_u64().unwrap() as usize,
  153. is_active: node1["is_active"].as_bool().unwrap(),
  154. last_message: node1["message"].to_string(),
  155. },
  156. //NodeInfo {
  157. // id: node2["id"].to_string(),
  158. // connections: node2["connections"].as_u64().unwrap() as usize,
  159. // is_active: node2["is_active"].as_bool().unwrap(),
  160. // last_message: node2["message"].to_string(),
  161. //},
  162. //NodeInfo {
  163. // id: node3["id"].to_string(),
  164. // connections: node3["connections"].as_u64().unwrap() as usize,
  165. // is_active: node3["is_active"].as_bool().unwrap(),
  166. // last_message: node3["message"].to_string(),
  167. //},
  168. ];
  169. for node in infos {
  170. // write nodes
  171. model.info_list.infos.lock().await.push(node.clone());
  172. // write node id
  173. model.id_list.node_id.lock().await.push(node.clone().id);
  174. }
  175. } else {
  176. // TODO: error handling
  177. println!("Reply is an error");
  178. }
  179. async_util::sleep(2).await;
  180. }
  181. }
  182. async fn render<B: Backend>(terminal: &mut Terminal<B>, model: Arc<Model>) -> io::Result<()> {
  183. let mut asi = async_stdin();
  184. terminal.clear()?;
  185. let mut info_vec = Vec::new();
  186. for info in model.info_list.infos.lock().await.clone() {
  187. info_vec.push(info)
  188. }
  189. let mut id_vec = Vec::new();
  190. for id in model.id_list.node_id.lock().await.clone() {
  191. id_vec.push(id)
  192. }
  193. let id_list = IdListView::new(id_vec);
  194. let info_list = InfoListView::new(info_vec);
  195. let mut view = View::new(id_list.clone(), info_list.clone());
  196. view.id_list.state.select(Some(0));
  197. view.info_list.index = 0;
  198. loop {
  199. let mut view = view.clone();
  200. view.update(
  201. model.id_list.node_id.lock().await.clone(),
  202. model.info_list.infos.lock().await.clone(),
  203. );
  204. async_util::sleep(1).await;
  205. terminal.draw(|f| {
  206. ui::ui(f, view.clone());
  207. })?;
  208. for k in asi.by_ref().keys() {
  209. match k.unwrap() {
  210. Key::Char('q') => {
  211. terminal.clear()?;
  212. return Ok(());
  213. }
  214. Key::Char('j') => {
  215. view.id_list.next();
  216. view.info_list.next().await;
  217. }
  218. Key::Char('k') => {
  219. view.id_list.previous();
  220. view.info_list.previous().await;
  221. }
  222. _ => (),
  223. }
  224. }
  225. }
  226. }