jsonrpc.rs 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  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<'_, HashSet<StoppableTaskPtr>> {
  61. self.rpc_connections.lock().await
  62. }
  63. }
  64. #[test]
  65. fn jsonrpc_reqrep() -> Result<()> {
  66. let executor = Arc::new(Executor::new());
  67. smol::block_on(executor.run(async {
  68. // Find an available port
  69. let listener = TcpListener::bind("127.0.0.1:0").await?;
  70. let sockaddr = listener.local_addr()?;
  71. let endpoint = Url::parse(&format!("tcp://127.0.0.1:{}", sockaddr.port()))?;
  72. drop(listener);
  73. let rpcsrv = Arc::new(RpcSrv {
  74. stop_sub: smol::channel::unbounded(),
  75. rpc_connections: Mutex::new(HashSet::new()),
  76. });
  77. let rpcsrv_ = Arc::clone(&rpcsrv);
  78. let rpc_task = StoppableTask::new();
  79. rpc_task.clone().start(
  80. listen_and_serve(endpoint.clone(), rpcsrv.clone(), None, executor.clone()),
  81. |res| async move {
  82. match res {
  83. Ok(()) | Err(Error::RpcServerStopped) => rpcsrv_.stop_connections().await,
  84. Err(e) => eprintln!("Failed starting JSON-RPC server: {}", e),
  85. }
  86. },
  87. Error::RpcServerStopped,
  88. executor.clone(),
  89. );
  90. msleep(500).await;
  91. let client = RpcClient::new(endpoint, executor.clone()).await?;
  92. let req = JsonRequest::new("ping", vec![].into());
  93. let rep = client.request(req).await?;
  94. let rep = String::try_from(rep).unwrap();
  95. assert_eq!(&rep, "pong");
  96. let req = JsonRequest::new("kill", vec![].into());
  97. let rep = client.request(req).await?;
  98. let rep = String::try_from(rep).unwrap();
  99. assert_eq!(&rep, "bye");
  100. Ok(())
  101. }))
  102. }