main.rs 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  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, info};
  13. use serde_json::{json, Value};
  14. use simplelog::*;
  15. use smol::Executor;
  16. use std::{
  17. collections::{HashMap, HashSet},
  18. fs::File,
  19. io,
  20. io::Read,
  21. path::PathBuf,
  22. };
  23. use termion::{async_stdin, event::Key, input::TermRead, raw::IntoRawMode};
  24. use tui::{
  25. backend::{Backend, TermionBackend},
  26. Terminal,
  27. };
  28. use url::Url;
  29. use map::{
  30. model::{Connection, IdList, InfoList, NodeInfo},
  31. options::ProgramOptions,
  32. ui,
  33. view::{IdListView, InfoListView},
  34. Model, View,
  35. };
  36. const CONFIG_FILE_CONTENTS: &[u8] = include_bytes!("../map_config.toml");
  37. struct Map {
  38. url: Url,
  39. }
  40. impl Map {
  41. pub fn new(url: Url) -> Self {
  42. Self { url }
  43. }
  44. async fn request(&self, r: jsonrpc::JsonRequest) -> Result<Value> {
  45. let reply: JsonResult = match jsonrpc::send_request(&self.url, json!(r)).await {
  46. Ok(v) => v,
  47. Err(e) => return Err(e),
  48. };
  49. match reply {
  50. JsonResult::Resp(r) => {
  51. debug!(target: "RPC", "<-- {}", serde_json::to_string(&r)?);
  52. Ok(r.result)
  53. }
  54. JsonResult::Err(e) => {
  55. debug!(target: "RPC", "<-- {}", serde_json::to_string(&e)?);
  56. Err(Error::JsonRpcError(e.error.message.to_string()))
  57. }
  58. JsonResult::Notif(n) => {
  59. debug!(target: "RPC", "<-- {}", serde_json::to_string(&n)?);
  60. Err(Error::JsonRpcError("Unexpected reply".to_string()))
  61. }
  62. }
  63. }
  64. // --> {"jsonrpc": "2.0", "method": "ping", "params": [], "id": 42}
  65. // <-- {"jsonrpc": "2.0", "result": "pong", "id": 42}
  66. async fn _ping(&self) -> Result<Value> {
  67. let req = jsonrpc::request(json!("ping"), json!([]));
  68. Ok(self.request(req).await?)
  69. }
  70. //--> {"jsonrpc": "2.0", "method": "poll", "params": [], "id": 42}
  71. // <-- {"jsonrpc": "2.0", "result": {"nodeID": [], "nodeinfo" [], "id": 42}
  72. async fn get_info(&self) -> Result<Value> {
  73. let req = jsonrpc::request(json!("get_info"), json!([]));
  74. Ok(self.request(req).await?)
  75. }
  76. }
  77. #[async_std::main]
  78. async fn main() -> Result<()> {
  79. let options = ProgramOptions::load()?;
  80. let (lvl, cfg) = log_config(options.app.clone())?;
  81. let file = File::create(&*options.log_path).unwrap();
  82. WriteLogger::init(lvl, cfg, file)?;
  83. info!("Log level: {}", lvl);
  84. let config_path = join_config_path(&PathBuf::from("map_config.toml"))?;
  85. spawn_config(&config_path, CONFIG_FILE_CONTENTS)?;
  86. let config = Config::<MapConfig>::load(config_path)?;
  87. let stdout = io::stdout().into_raw_mode()?;
  88. let backend = TermionBackend::new(stdout);
  89. let mut terminal = Terminal::new(backend)?;
  90. terminal.clear()?;
  91. let info_list = InfoList::new();
  92. let ids = HashSet::new();
  93. let id_list = IdList::new(ids);
  94. let model = Arc::new(Model::new(id_list, info_list));
  95. let nthreads = num_cpus::get();
  96. let (signal, shutdown) = async_channel::unbounded::<()>();
  97. let ex = Arc::new(Executor::new());
  98. let ex2 = ex.clone();
  99. let (_, result) = Parallel::new()
  100. .each(0..nthreads, |_| smol::future::block_on(ex.run(shutdown.recv())))
  101. .finish(|| {
  102. smol::future::block_on(async move {
  103. run_rpc(&config, ex2.clone(), model.clone()).await?;
  104. render(&mut terminal, model.clone()).await?;
  105. drop(signal);
  106. Ok::<(), darkfi::Error>(())
  107. })
  108. });
  109. result
  110. }
  111. async fn run_rpc(config: &MapConfig, ex: Arc<Executor<'_>>, model: Arc<Model>) -> Result<()> {
  112. let mut rpc_vec = Vec::new();
  113. for node in config.nodes.clone() {
  114. rpc_vec.push(node);
  115. }
  116. for node in rpc_vec {
  117. debug!("Created client: {}", node.node_id);
  118. let client = Map::new(Url::parse(&node.node_id)?);
  119. ex.spawn(poll(client, model.clone())).detach();
  120. }
  121. Ok(())
  122. }
  123. async fn poll(client: Map, model: Arc<Model>) -> Result<()> {
  124. debug!("Attemping to poll: {}", client.url);
  125. // TODO: fix this! this can lag forever
  126. // check connect() on net/connector.rs
  127. //let reply = client.ping().await?;
  128. //if reply.as_str().is_some() {
  129. let mut index = 0;
  130. loop {
  131. //debug!("Connected to: {}", client.url);
  132. let reply = client.get_info().await?;
  133. if reply.as_object().is_some() && !reply.as_object().unwrap().is_empty() {
  134. let id = reply.as_object().unwrap().get("id").unwrap();
  135. let connections = reply.as_object().unwrap().get("connections").unwrap();
  136. let outgoing = connections.get("outgoing").unwrap();
  137. let incoming = connections.get("incoming").unwrap();
  138. let mut outconnects = Vec::new();
  139. let mut inconnects = Vec::new();
  140. // here we are simulating new messages by scrolling through a vector
  141. let msgs = outgoing[1].get("message").unwrap();
  142. if index == 0 {
  143. index += 1;
  144. } else if index >= 5 {
  145. index = 0
  146. } else {
  147. index = index + 1;
  148. }
  149. let out0 = Connection::new(
  150. outgoing[0].get("id").unwrap().as_str().unwrap().to_string(),
  151. msgs[index].as_str().unwrap().to_string(),
  152. );
  153. let out1 = Connection::new(
  154. outgoing[1].get("id").unwrap().as_str().unwrap().to_string(),
  155. msgs[index].as_str().unwrap().to_string(),
  156. );
  157. let in0 = Connection::new(
  158. incoming[0].get("id").unwrap().as_str().unwrap().to_string(),
  159. msgs[index].as_str().unwrap().to_string(),
  160. );
  161. let in1 = Connection::new(
  162. incoming[1].get("id").unwrap().as_str().unwrap().to_string(),
  163. msgs[index].as_str().unwrap().to_string(),
  164. );
  165. outconnects.push(out0);
  166. outconnects.push(out1);
  167. inconnects.push(in0);
  168. inconnects.push(in1);
  169. let infos = NodeInfo { outgoing: outconnects, incoming: inconnects };
  170. let mut node_info = HashMap::new();
  171. node_info.insert(id.as_str().unwrap().to_string(), infos);
  172. for (id, value) in node_info.clone() {
  173. model.id_list.node_id.lock().await.insert(id.clone());
  174. model.info_list.infos.lock().await.insert(id, value);
  175. }
  176. } else {
  177. // TODO: error handling
  178. debug!("Reply is empty");
  179. }
  180. async_util::sleep(2).await;
  181. }
  182. //} else {
  183. // async_util::sleep(10).await;
  184. // Err(Error::ConnectTimeout)
  185. //}
  186. }
  187. async fn render<B: Backend>(terminal: &mut Terminal<B>, model: Arc<Model>) -> io::Result<()> {
  188. let mut asi = async_stdin();
  189. terminal.clear()?;
  190. let id_list = IdListView::new(HashSet::new());
  191. let info_list = InfoListView::new(HashMap::new());
  192. let mut view = View::new(id_list.clone(), info_list.clone());
  193. view.id_list.state.select(Some(0));
  194. view.info_list.index = 0;
  195. //let mut counter = 0;
  196. loop {
  197. //counter = counter + 1;
  198. view.update(model.info_list.infos.lock().await.clone());
  199. //if view.id_list.node_id.is_empty() {
  200. // // TODO: delete this and display empty data
  201. // if counter == 1 {
  202. // let mut progress = 0;
  203. // while progress < 100 {
  204. // terminal.draw(|f| {
  205. // ui::init_panel(f, progress);
  206. // })?;
  207. // Timer::after(Duration::from_millis(1)).await;
  208. // progress = progress + 1;
  209. // }
  210. // } else if counter == 2 {
  211. // terminal.clear()?;
  212. // // TODO: continue to display not, mark as offline
  213. // println!("Could not connect to node. Are you sure RPC is running?");
  214. // }
  215. //} else {
  216. terminal.draw(|f| {
  217. ui::ui(f, view.clone());
  218. })?;
  219. //}
  220. for k in asi.by_ref().keys() {
  221. match k.unwrap() {
  222. Key::Char('q') => {
  223. terminal.clear()?;
  224. return Ok(());
  225. }
  226. Key::Char('j') => {
  227. view.id_list.next();
  228. view.info_list.next().await;
  229. }
  230. Key::Char('k') => {
  231. view.id_list.previous();
  232. view.info_list.previous().await;
  233. }
  234. _ => (),
  235. }
  236. }
  237. }
  238. }