main.rs 9.0 KB

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