server.rs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2023 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, io::ErrorKind, sync::Arc};
  19. use async_trait::async_trait;
  20. use log::{debug, error, info};
  21. use smol::{
  22. io::{BufReader, ReadHalf, WriteHalf},
  23. lock::{Mutex, MutexGuard},
  24. };
  25. use tinyjson::JsonValue;
  26. use url::Url;
  27. use super::{
  28. common::{read_from_stream, write_to_stream, INIT_BUF_SIZE},
  29. jsonrpc::*,
  30. };
  31. use crate::{
  32. net::transport::{Listener, PtListener, PtStream},
  33. system::{StoppableTask, StoppableTaskPtr},
  34. Error, Result,
  35. };
  36. /// Asynchronous trait implementing a handler for incoming JSON-RPC requests.
  37. #[async_trait]
  38. pub trait RequestHandler: Sync + Send {
  39. async fn handle_request(&self, req: JsonRequest) -> JsonResult;
  40. async fn pong(&self, id: u16, _params: JsonValue) -> JsonResult {
  41. JsonResponse::new(JsonValue::String("pong".to_string()), id).into()
  42. }
  43. async fn connections_mut(&self) -> MutexGuard<'_, HashSet<StoppableTaskPtr>>;
  44. async fn connections(&self) -> Vec<StoppableTaskPtr> {
  45. self.connections_mut().await.iter().cloned().collect()
  46. }
  47. async fn mark_connection(&self, task: StoppableTaskPtr) {
  48. self.connections_mut().await.insert(task);
  49. }
  50. async fn unmark_connection(&self, task: StoppableTaskPtr) {
  51. self.connections_mut().await.remove(&task);
  52. }
  53. async fn active_connections(&self) -> usize {
  54. self.connections_mut().await.len()
  55. }
  56. async fn stop_connections(&self) {
  57. info!(target: "rpc::server", "[RPC] Server stopped, closing connections");
  58. for (i, task) in self.connections().await.iter().enumerate() {
  59. debug!(target: "rpc::server", "Stopping connection #{}", i);
  60. task.stop().await;
  61. }
  62. }
  63. }
  64. /// Accept function that should run inside a loop for accepting incoming
  65. /// JSON-RPC requests and passing them to the [`RequestHandler`].
  66. #[allow(clippy::type_complexity)]
  67. pub async fn accept(
  68. reader: Arc<Mutex<BufReader<ReadHalf<Box<dyn PtStream>>>>>,
  69. writer: Arc<Mutex<WriteHalf<Box<dyn PtStream>>>>,
  70. addr: Url,
  71. rh: Arc<impl RequestHandler + 'static>,
  72. conn_limit: Option<usize>,
  73. ex: Arc<smol::Executor<'_>>,
  74. ) -> Result<()> {
  75. // If there's a connection limit set, we will refuse connections
  76. // after this point.
  77. if let Some(conn_limit) = conn_limit {
  78. if rh.clone().active_connections().await >= conn_limit {
  79. debug!(
  80. target: "rpc::server::accept()",
  81. "Connection limit reached, refusing new conn"
  82. );
  83. return Err(Error::RpcConnectionsExhausted)
  84. }
  85. }
  86. // We'll hold our background tasks here
  87. let tasks = Arc::new(Mutex::new(HashSet::new()));
  88. loop {
  89. let mut buf = Vec::with_capacity(INIT_BUF_SIZE);
  90. let mut reader_lock = reader.lock().await;
  91. let _ = read_from_stream(&mut reader_lock, &mut buf, false).await?;
  92. drop(reader_lock);
  93. let line = match String::from_utf8(buf) {
  94. Ok(v) => v,
  95. Err(e) => {
  96. error!(
  97. target: "rpc::server::accept()",
  98. "[RPC SERVER] Failed parsing string from read buffer: {}", e,
  99. );
  100. return Err(e.into())
  101. }
  102. };
  103. // Parse the line as JSON
  104. let val: JsonValue = match line.trim().parse() {
  105. Ok(v) => v,
  106. Err(e) => {
  107. error!(
  108. target: "rpc::server::accept()",
  109. "[RPC SERVER] Failed parsing JSON string: {}", e,
  110. );
  111. return Err(e.into())
  112. }
  113. };
  114. // Cast to JsonRequest
  115. let req = match JsonRequest::try_from(&val) {
  116. Ok(v) => v,
  117. Err(e) => {
  118. error!(
  119. target: "rpc::server::accept()",
  120. "[RPC SERVER] Failed casting JSON to a JsonRequest: {}", e,
  121. );
  122. return Err(e.into())
  123. }
  124. };
  125. debug!(target: "rpc::server", "{} --> {}", addr, val.stringify()?);
  126. let rep = rh.handle_request(req).await;
  127. match rep {
  128. JsonResult::Subscriber(subscriber) => {
  129. let task = StoppableTask::new();
  130. // Clone what needs to go in the background
  131. let task_ = task.clone();
  132. let addr_ = addr.clone();
  133. let tasks_ = tasks.clone();
  134. let writer_ = writer.clone();
  135. // Detach the subscriber so we can multiplex further requests
  136. task.clone().start(
  137. async move {
  138. // Subscribe to the inner method subscriber
  139. let subscription = subscriber.sub.subscribe().await;
  140. loop {
  141. // Listen for notifications
  142. let notification = subscription.receive().await;
  143. // Push notification
  144. debug!(target: "rpc::server", "{} <-- {}", addr_, notification.stringify()?);
  145. let notification = JsonResult::Notification(notification);
  146. let mut writer_lock = writer_.lock().await;
  147. if let Err(e) = write_to_stream(&mut writer_lock, &notification).await {
  148. subscription.unsubscribe().await;
  149. return Err(e)
  150. }
  151. drop(writer_lock);
  152. }
  153. },
  154. move |_| async move {
  155. debug!(
  156. target: "rpc::server",
  157. "Removing background task {} from map", task_.task_id,
  158. );
  159. tasks_.lock().await.remove(&task_);
  160. },
  161. Error::DetachedTaskStopped,
  162. ex.clone(),
  163. );
  164. debug!(target: "rpc::server", "Adding background task {} to map", task.task_id);
  165. tasks.lock().await.insert(task.clone());
  166. }
  167. JsonResult::SubscriberWithReply(subscriber, reply) => {
  168. // Write the response
  169. debug!(target: "rpc::server", "{} <-- {}", addr, reply.stringify()?);
  170. let mut writer_lock = writer.lock().await;
  171. write_to_stream(&mut writer_lock, &reply.into()).await?;
  172. drop(writer_lock);
  173. let task = StoppableTask::new();
  174. // Clone what needs to go in the background
  175. let task_ = task.clone();
  176. let addr_ = addr.clone();
  177. let tasks_ = tasks.clone();
  178. let writer_ = writer.clone();
  179. // Detach the subscriber so we can multiplex further requests
  180. task.clone().start(
  181. async move {
  182. // Start the subscriber loop
  183. let subscription = subscriber.sub.subscribe().await;
  184. loop {
  185. // Listen for notifications
  186. let notification = subscription.receive().await;
  187. // Push notification
  188. debug!(target: "rpc::server", "{} <-- {}", addr_, notification.stringify()?);
  189. let notification = JsonResult::Notification(notification);
  190. let mut writer_lock = writer_.lock().await;
  191. if let Err(e) = write_to_stream(&mut writer_lock, &notification).await {
  192. subscription.unsubscribe().await;
  193. drop(writer_lock);
  194. return Err(e)
  195. }
  196. drop(writer_lock);
  197. }
  198. },
  199. move |_| async move {
  200. debug!(
  201. target: "rpc::server",
  202. "Removing background task {} from map", task_.task_id,
  203. );
  204. tasks_.lock().await.remove(&task_);
  205. },
  206. Error::DetachedTaskStopped,
  207. ex.clone(),
  208. );
  209. debug!(target: "rpc::server", "Adding background task {} to map", task.task_id);
  210. tasks.lock().await.insert(task.clone());
  211. }
  212. JsonResult::Request(_) | JsonResult::Notification(_) => {
  213. unreachable!("Should never happen")
  214. }
  215. JsonResult::Response(ref v) => {
  216. debug!(target: "rpc::server", "{} <-- {}", addr, v.stringify()?);
  217. let mut writer_lock = writer.lock().await;
  218. write_to_stream(&mut writer_lock, &rep).await?;
  219. drop(writer_lock);
  220. }
  221. JsonResult::Error(ref v) => {
  222. debug!(target: "rpc::server", "{} <-- {}", addr, v.stringify()?);
  223. let mut writer_lock = writer.lock().await;
  224. write_to_stream(&mut writer_lock, &rep).await?;
  225. drop(writer_lock);
  226. }
  227. }
  228. }
  229. }
  230. /// Wrapper function around [`accept()`] to take the incoming connection and
  231. /// pass it forward.
  232. async fn run_accept_loop(
  233. listener: Box<dyn PtListener>,
  234. rh: Arc<impl RequestHandler + 'static>,
  235. conn_limit: Option<usize>,
  236. ex: Arc<smol::Executor<'_>>,
  237. ) -> Result<()> {
  238. loop {
  239. match listener.next().await {
  240. Ok((stream, url)) => {
  241. let rh_ = rh.clone();
  242. info!(target: "rpc::server", "[RPC] Server accepted conn from {}", url);
  243. let (reader, writer) = smol::io::split(stream);
  244. let reader = Arc::new(Mutex::new(BufReader::new(reader)));
  245. let writer = Arc::new(Mutex::new(writer));
  246. let task = StoppableTask::new();
  247. let task_ = task.clone();
  248. let ex_ = ex.clone();
  249. task.clone().start(
  250. accept(reader, writer, url.clone(), rh.clone(), conn_limit, ex_),
  251. |_| async move {
  252. rh_.clone().unmark_connection(task_.clone()).await;
  253. },
  254. Error::ChannelStopped,
  255. ex.clone(),
  256. );
  257. rh.clone().mark_connection(task.clone()).await;
  258. }
  259. // As per accept(2) recommendation:
  260. Err(e) if e.raw_os_error().is_some() => match e.raw_os_error().unwrap() {
  261. libc::EAGAIN | libc::ECONNABORTED | libc::EPROTO | libc::EINTR => continue,
  262. _ => {
  263. error!(
  264. target: "rpc::server::run_accept_loop()",
  265. "[RPC] Server failed listening: {}", e,
  266. );
  267. error!(
  268. target: "rpc::server::run_accept_loop()",
  269. "[RPC] Closing accept loop"
  270. );
  271. return Err(e.into())
  272. }
  273. },
  274. // In case a TLS handshake fails, we'll get this:
  275. Err(e) if e.kind() == ErrorKind::UnexpectedEof => continue,
  276. // Errors we didn't handle above:
  277. Err(e) => {
  278. error!(
  279. target: "rpc::server::run_accept_loop()",
  280. "[RPC] Unhandled listener.next() error: {}", e,
  281. );
  282. error!(
  283. target: "rpc::server::run_accept_loop()",
  284. "[RPC] Closing acceptloop"
  285. );
  286. return Err(e.into())
  287. }
  288. }
  289. }
  290. }
  291. /// Start a JSON-RPC server bound to the given accept URL and use the
  292. /// given [`RequestHandler`] to handle incoming requests.
  293. pub async fn listen_and_serve(
  294. accept_url: Url,
  295. rh: Arc<impl RequestHandler + 'static>,
  296. conn_limit: Option<usize>,
  297. ex: Arc<smol::Executor<'_>>,
  298. ) -> Result<()> {
  299. let listener = Listener::new(accept_url).await?.listen().await?;
  300. run_accept_loop(listener, rh, conn_limit, ex.clone()).await
  301. }
  302. #[cfg(test)]
  303. mod tests {
  304. use super::*;
  305. use crate::{rpc::client::RpcClient, system::msleep};
  306. use smol::{lock::Mutex, net::TcpListener, Executor};
  307. struct RpcServer {
  308. rpc_connections: Mutex<HashSet<StoppableTaskPtr>>,
  309. }
  310. #[async_trait]
  311. impl RequestHandler for RpcServer {
  312. async fn handle_request(&self, req: JsonRequest) -> JsonResult {
  313. match req.method.as_str() {
  314. "ping" => return self.pong(req.id, req.params).await,
  315. _ => panic!(),
  316. }
  317. }
  318. async fn connections_mut(&self) -> MutexGuard<'_, HashSet<StoppableTaskPtr>> {
  319. self.rpc_connections.lock().await
  320. }
  321. }
  322. #[test]
  323. fn conn_manager() -> Result<()> {
  324. let executor = Arc::new(Executor::new());
  325. // This simulates a server and a client. Through the function, there
  326. // are some calls to sleep(), which are used for the tests, because
  327. // otherwise they execute too fast. In practice, The RPC server is
  328. // a long-running task so when polled, it should handle things in a
  329. // correct manner.
  330. smol::block_on(executor.run(async {
  331. // Find an available port
  332. let listener = TcpListener::bind("127.0.0.1:0").await?;
  333. let sockaddr = listener.local_addr()?;
  334. let endpoint = Url::parse(&format!("tcp://127.0.0.1:{}", sockaddr.port()))?;
  335. drop(listener);
  336. let rpc_server = Arc::new(RpcServer { rpc_connections: Mutex::new(HashSet::new()) });
  337. let rpc_server_ = rpc_server.clone();
  338. let server_task = StoppableTask::new();
  339. server_task.clone().start(
  340. listen_and_serve(endpoint.clone(), rpc_server.clone(), None, executor.clone()),
  341. |res| async move {
  342. match res {
  343. Ok(()) | Err(Error::RpcServerStopped) => {
  344. rpc_server_.stop_connections().await
  345. }
  346. Err(e) => panic!("{}", e),
  347. }
  348. },
  349. Error::RpcServerStopped,
  350. executor.clone(),
  351. );
  352. // Let the server spawn
  353. msleep(500).await;
  354. // Connect a client
  355. let rpc_client0 = RpcClient::new(endpoint.clone(), executor.clone()).await?;
  356. msleep(500).await;
  357. assert!(rpc_server.active_connections().await == 1);
  358. // Connect another client
  359. let rpc_client1 = RpcClient::new(endpoint.clone(), executor.clone()).await?;
  360. msleep(500).await;
  361. assert!(rpc_server.active_connections().await == 2);
  362. // And another one
  363. let _rpc_client2 = RpcClient::new(endpoint.clone(), executor.clone()).await?;
  364. msleep(500).await;
  365. assert!(rpc_server.active_connections().await == 3);
  366. // Close the first client
  367. rpc_client0.stop().await;
  368. msleep(500).await;
  369. assert!(rpc_server.active_connections().await == 2);
  370. // Close the second client
  371. rpc_client1.stop().await;
  372. msleep(500).await;
  373. assert!(rpc_server.active_connections().await == 1);
  374. // The Listener should be stopped when we stop the server task.
  375. server_task.stop().await;
  376. assert!(RpcClient::new(endpoint, executor.clone()).await.is_err());
  377. // After the server is stopped, the connections tasks should also be stopped
  378. assert!(rpc_server.active_connections().await == 0);
  379. Ok(())
  380. }))
  381. }
  382. }