server.rs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  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, 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).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.publisher.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().unwrap());
  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.into())
  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.publisher.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().unwrap());
  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.into())
  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. info!(target: "rpc::server", "[RPC] Closed conn from {}", url);
  253. rh_.clone().unmark_connection(task_.clone()).await;
  254. },
  255. Error::ChannelStopped,
  256. ex.clone(),
  257. );
  258. rh.clone().mark_connection(task.clone()).await;
  259. }
  260. // As per accept(2) recommendation:
  261. Err(e) if e.raw_os_error().is_some() => match e.raw_os_error().unwrap() {
  262. libc::EAGAIN | libc::ECONNABORTED | libc::EPROTO | libc::EINTR => continue,
  263. _ => {
  264. error!(
  265. target: "rpc::server::run_accept_loop()",
  266. "[RPC] Server failed listening: {}", e,
  267. );
  268. error!(
  269. target: "rpc::server::run_accept_loop()",
  270. "[RPC] Closing accept loop"
  271. );
  272. return Err(e.into())
  273. }
  274. },
  275. // In case a TLS handshake fails, we'll get this:
  276. Err(e) if e.kind() == ErrorKind::UnexpectedEof => continue,
  277. // Errors we didn't handle above:
  278. Err(e) => {
  279. error!(
  280. target: "rpc::server::run_accept_loop()",
  281. "[RPC] Unhandled listener.next() error: {}", e,
  282. );
  283. error!(
  284. target: "rpc::server::run_accept_loop()",
  285. "[RPC] Closing acceptloop"
  286. );
  287. return Err(e.into())
  288. }
  289. }
  290. }
  291. }
  292. /// Start a JSON-RPC server bound to the given accept URL and use the
  293. /// given [`RequestHandler`] to handle incoming requests.
  294. pub async fn listen_and_serve(
  295. accept_url: Url,
  296. rh: Arc<impl RequestHandler + 'static>,
  297. conn_limit: Option<usize>,
  298. ex: Arc<smol::Executor<'_>>,
  299. ) -> Result<()> {
  300. let listener = Listener::new(accept_url).await?.listen().await?;
  301. run_accept_loop(listener, rh, conn_limit, ex.clone()).await
  302. }
  303. #[cfg(test)]
  304. mod tests {
  305. use super::*;
  306. use crate::{rpc::client::RpcClient, system::msleep};
  307. use smol::{net::TcpListener, Executor};
  308. struct RpcServer {
  309. rpc_connections: Mutex<HashSet<StoppableTaskPtr>>,
  310. }
  311. #[async_trait]
  312. impl RequestHandler for RpcServer {
  313. async fn handle_request(&self, req: JsonRequest) -> JsonResult {
  314. match req.method.as_str() {
  315. "ping" => return self.pong(req.id, req.params).await,
  316. _ => panic!(),
  317. }
  318. }
  319. async fn connections_mut(&self) -> MutexGuard<'_, HashSet<StoppableTaskPtr>> {
  320. self.rpc_connections.lock().await
  321. }
  322. }
  323. #[test]
  324. fn conn_manager() -> Result<()> {
  325. let executor = Arc::new(Executor::new());
  326. // This simulates a server and a client. Through the function, there
  327. // are some calls to sleep(), which are used for the tests, because
  328. // otherwise they execute too fast. In practice, The RPC server is
  329. // a long-running task so when polled, it should handle things in a
  330. // correct manner.
  331. smol::block_on(executor.run(async {
  332. // Find an available port
  333. let listener = TcpListener::bind("127.0.0.1:0").await?;
  334. let sockaddr = listener.local_addr()?;
  335. let endpoint = Url::parse(&format!("tcp://127.0.0.1:{}", sockaddr.port()))?;
  336. drop(listener);
  337. let rpc_server = Arc::new(RpcServer { rpc_connections: Mutex::new(HashSet::new()) });
  338. let rpc_server_ = rpc_server.clone();
  339. let server_task = StoppableTask::new();
  340. server_task.clone().start(
  341. listen_and_serve(endpoint.clone(), rpc_server.clone(), None, executor.clone()),
  342. |res| async move {
  343. match res {
  344. Ok(()) | Err(Error::RpcServerStopped) => {
  345. rpc_server_.stop_connections().await
  346. }
  347. Err(e) => panic!("{}", e),
  348. }
  349. },
  350. Error::RpcServerStopped,
  351. executor.clone(),
  352. );
  353. // Let the server spawn
  354. msleep(500).await;
  355. // Connect a client
  356. let rpc_client0 = RpcClient::new(endpoint.clone(), executor.clone()).await?;
  357. msleep(500).await;
  358. assert!(rpc_server.active_connections().await == 1);
  359. // Connect another client
  360. let rpc_client1 = RpcClient::new(endpoint.clone(), executor.clone()).await?;
  361. msleep(500).await;
  362. assert!(rpc_server.active_connections().await == 2);
  363. // And another one
  364. let _rpc_client2 = RpcClient::new(endpoint.clone(), executor.clone()).await?;
  365. msleep(500).await;
  366. assert!(rpc_server.active_connections().await == 3);
  367. // Close the first client
  368. rpc_client0.stop().await;
  369. msleep(500).await;
  370. assert!(rpc_server.active_connections().await == 2);
  371. // Close the second client
  372. rpc_client1.stop().await;
  373. msleep(500).await;
  374. assert!(rpc_server.active_connections().await == 1);
  375. // The Listener should be stopped when we stop the server task.
  376. server_task.stop().await;
  377. assert!(RpcClient::new(endpoint, executor.clone()).await.is_err());
  378. // After the server is stopped, the connections tasks should also be stopped
  379. assert!(rpc_server.active_connections().await == 0);
  380. Ok(())
  381. }))
  382. }
  383. }