jsonrpc.rs 3.4 KB

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