jsonrpc.rs 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  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, 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. net::transport::Listener,
  30. rpc::{
  31. client::RpcClient,
  32. jsonrpc::*,
  33. server::{accept, RequestHandler},
  34. },
  35. system::StoppableTaskPtr,
  36. Result,
  37. };
  38. struct RpcSrv {
  39. stop_sub: (Sender<()>, Receiver<()>),
  40. rpc_connections: Mutex<HashSet<StoppableTaskPtr>>,
  41. }
  42. impl RpcSrv {
  43. async fn pong(&self, id: u16, _params: JsonValue) -> JsonResult {
  44. JsonResponse::new(JsonValue::String("pong".to_string()), id).into()
  45. }
  46. async fn kill(&self, id: u16, _params: JsonValue) -> JsonResult {
  47. self.stop_sub.0.send(()).await.unwrap();
  48. JsonResponse::new(JsonValue::String("bye".to_string()), id).into()
  49. }
  50. }
  51. #[async_trait]
  52. impl RequestHandler for RpcSrv {
  53. async fn handle_request(&self, req: JsonRequest) -> JsonResult {
  54. assert!(req.params.is_array());
  55. match req.method.as_str() {
  56. "ping" => return self.pong(req.id, req.params).await,
  57. "kill" => return self.kill(req.id, req.params).await,
  58. _ => return JsonError::new(ErrorCode::MethodNotFound, None, req.id).into(),
  59. }
  60. }
  61. async fn connections_mut(&self) -> MutexGuard<'_, HashSet<StoppableTaskPtr>> {
  62. self.rpc_connections.lock().await
  63. }
  64. }
  65. #[test]
  66. fn jsonrpc_reqrep() -> Result<()> {
  67. let executor = Arc::new(Executor::new());
  68. let executor_ = executor.clone();
  69. smol::block_on(executor.run(async {
  70. // Find an available port
  71. let listener = TcpListener::bind("127.0.0.1:0").await?;
  72. let sockaddr = listener.local_addr()?;
  73. let endpoint = Url::parse(&format!("tcp://127.0.0.1:{}", sockaddr.port()))?;
  74. drop(listener);
  75. let rpcsrv = Arc::new(RpcSrv {
  76. stop_sub: smol::channel::unbounded(),
  77. rpc_connections: Mutex::new(HashSet::new()),
  78. });
  79. let listener = Listener::new(endpoint.clone()).await?.listen().await?;
  80. executor
  81. .spawn(async move {
  82. while let Ok((stream, peer_addr)) = listener.next().await {
  83. let rh_ = rpcsrv.clone();
  84. executor_
  85. .spawn(async move {
  86. let _ = accept(stream, peer_addr.clone(), rh_, None).await;
  87. })
  88. .detach();
  89. }
  90. })
  91. .detach();
  92. let client = RpcClient::new(endpoint, executor.clone()).await?;
  93. let req = JsonRequest::new("ping", vec![]);
  94. let rep = client.request(req).await?;
  95. let rep = String::try_from(rep).unwrap();
  96. assert_eq!(&rep, "pong");
  97. let req = JsonRequest::new("kill", vec![]);
  98. let rep = client.request(req).await?;
  99. let rep = String::try_from(rep).unwrap();
  100. assert_eq!(&rep, "bye");
  101. Ok(())
  102. }))
  103. }