jsonrpc.rs 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2024 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use std::{collections::HashSet, sync::Arc};
  19. use async_trait::async_trait;
  20. use smol::{
  21. channel::{Receiver, Sender},
  22. lock::{Mutex, MutexGuard},
  23. net::TcpListener,
  24. Executor,
  25. };
  26. use tinyjson::JsonValue;
  27. use url::Url;
  28. use darkfi::{
  29. rpc::{
  30. client::RpcClient,
  31. jsonrpc::*,
  32. server::{listen_and_serve, RequestHandler},
  33. },
  34. system::{msleep, StoppableTask, StoppableTaskPtr},
  35. Error, Result,
  36. };
  37. struct RpcSrv {
  38. stop_sub: (Sender<()>, Receiver<()>),
  39. rpc_connections: Mutex<HashSet<StoppableTaskPtr>>,
  40. }
  41. impl RpcSrv {
  42. async fn pong(&self, id: u16, _params: JsonValue) -> JsonResult {
  43. JsonResponse::new(JsonValue::String("pong".to_string()), id).into()
  44. }
  45. async fn kill(&self, id: u16, _params: JsonValue) -> JsonResult {
  46. self.stop_sub.0.send(()).await.unwrap();
  47. JsonResponse::new(JsonValue::String("bye".to_string()), id).into()
  48. }
  49. }
  50. #[async_trait]
  51. impl RequestHandler for RpcSrv {
  52. async fn handle_request(&self, req: JsonRequest) -> JsonResult {
  53. assert!(req.params.is_array());
  54. return match req.method.as_str() {
  55. "ping" => self.pong(req.id, req.params).await,
  56. "kill" => self.kill(req.id, req.params).await,
  57. _ => JsonError::new(ErrorCode::MethodNotFound, None, req.id).into(),
  58. }
  59. }
  60. async fn connections_mut(&self) -> MutexGuard<'life0, HashSet<StoppableTaskPtr>> {
  61. self.rpc_connections.lock().await
  62. }
  63. }
  64. /// Initialize the logging mechanism
  65. fn init_logger() {
  66. let mut cfg = simplelog::ConfigBuilder::new();
  67. // We check this error so we can execute same file tests in parallel,
  68. // otherwise second one fails to init logger here.
  69. if simplelog::TermLogger::init(
  70. //simplelog::LevelFilter::Info,
  71. simplelog::LevelFilter::Debug,
  72. //simplelog::LevelFilter::Trace,
  73. cfg.build(),
  74. simplelog::TerminalMode::Mixed,
  75. simplelog::ColorChoice::Auto,
  76. )
  77. .is_err()
  78. {
  79. log::debug!("Logger initialized");
  80. }
  81. }
  82. #[test]
  83. fn jsonrpc_reqrep() -> Result<()> {
  84. init_logger();
  85. let executor = Arc::new(Executor::new());
  86. smol::block_on(executor.run(async {
  87. // Find an available port
  88. let listener = TcpListener::bind("127.0.0.1:0").await?;
  89. let sockaddr = listener.local_addr()?;
  90. let endpoint = Url::parse(&format!("tcp://127.0.0.1:{}", sockaddr.port()))?;
  91. drop(listener);
  92. let rpcsrv = Arc::new(RpcSrv {
  93. stop_sub: smol::channel::unbounded(),
  94. rpc_connections: Mutex::new(HashSet::new()),
  95. });
  96. let rpcsrv_ = Arc::clone(&rpcsrv);
  97. let rpc_task = StoppableTask::new();
  98. rpc_task.clone().start(
  99. listen_and_serve(endpoint.clone(), rpcsrv.clone(), None, executor.clone()),
  100. |res| async move {
  101. match res {
  102. Ok(()) | Err(Error::RpcServerStopped) => rpcsrv_.stop_connections().await,
  103. Err(e) => eprintln!("Failed starting JSON-RPC server: {}", e),
  104. }
  105. },
  106. Error::RpcServerStopped,
  107. executor.clone(),
  108. );
  109. msleep(500).await;
  110. let client = RpcClient::new(endpoint, executor.clone()).await?;
  111. let req = JsonRequest::new("ping", vec![].into());
  112. let rep = client.request(req).await?;
  113. let rep = String::try_from(rep).unwrap();
  114. assert_eq!(&rep, "pong");
  115. let req = JsonRequest::new("kill", vec![].into());
  116. let rep = client.request(req).await?;
  117. let rep = String::try_from(rep).unwrap();
  118. assert_eq!(&rep, "bye");
  119. Ok(())
  120. }))
  121. }
  122. #[test]
  123. fn http_jsonrpc_reqrep() -> Result<()> {
  124. init_logger();
  125. let executor = Arc::new(Executor::new());
  126. smol::block_on(executor.run(async {
  127. // Find an available port
  128. let listener = TcpListener::bind("127.0.0.1:0").await?;
  129. let sockaddr = listener.local_addr()?;
  130. let endpoint = Url::parse(&format!("http+tcp://127.0.0.1:{}", sockaddr.port()))?;
  131. drop(listener);
  132. let rpcsrv = Arc::new(RpcSrv {
  133. stop_sub: smol::channel::unbounded(),
  134. rpc_connections: Mutex::new(HashSet::new()),
  135. });
  136. let rpcsrv_ = Arc::clone(&rpcsrv);
  137. let rpc_task = StoppableTask::new();
  138. rpc_task.clone().start(
  139. listen_and_serve(endpoint.clone(), rpcsrv.clone(), None, executor.clone()),
  140. |res| async move {
  141. match res {
  142. Ok(()) | Err(Error::RpcServerStopped) => rpcsrv_.stop_connections().await,
  143. Err(e) => eprintln!("Failed starting JSON-RPC server: {}", e),
  144. }
  145. },
  146. Error::RpcServerStopped,
  147. executor.clone(),
  148. );
  149. msleep(500).await;
  150. let client = RpcClient::new(endpoint, executor.clone()).await?;
  151. let req = JsonRequest::new("ping", vec![].into());
  152. let rep = client.request(req).await?;
  153. let rep = String::try_from(rep).unwrap();
  154. assert_eq!(&rep, "pong");
  155. let req = JsonRequest::new("kill", vec![].into());
  156. let rep = client.request(req).await?;
  157. let rep = String::try_from(rep).unwrap();
  158. assert_eq!(&rep, "bye");
  159. Ok(())
  160. }))
  161. }