server.rs 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  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 async_std::sync::Arc;
  19. use async_trait::async_trait;
  20. use serde_json::{json, Value};
  21. use smol::{
  22. channel::{Receiver, Sender},
  23. Executor,
  24. };
  25. use url::Url;
  26. use darkfi::{
  27. rpc::{
  28. jsonrpc::{ErrorCode, JsonError, JsonRequest, JsonResponse, JsonResult},
  29. server::{listen_and_serve, RequestHandler},
  30. },
  31. Result,
  32. };
  33. struct RpcSrv {
  34. stop_sub: (Sender<()>, Receiver<()>),
  35. }
  36. impl RpcSrv {
  37. async fn pong(&self, id: Value, _params: &[Value]) -> JsonResult {
  38. JsonResponse::new(json!("pong"), id).into()
  39. }
  40. async fn kill(&self, id: Value, _params: &[Value]) -> JsonResult {
  41. self.stop_sub.0.send(()).await.unwrap();
  42. JsonResponse::new(json!("Bye"), id).into()
  43. }
  44. }
  45. #[async_trait]
  46. impl RequestHandler for RpcSrv {
  47. async fn handle_request(&self, req: JsonRequest) -> JsonResult {
  48. if !req.params.is_array() {
  49. return JsonError::new(ErrorCode::InvalidParams, None, req.id).into()
  50. }
  51. let params = req.params.as_array().unwrap();
  52. match req.method.as_str() {
  53. Some("ping") => return self.pong(req.id, params).await,
  54. Some("kill") => return self.kill(req.id, params).await,
  55. Some(_) | None => return JsonError::new(ErrorCode::MethodNotFound, None, req.id).into(),
  56. }
  57. }
  58. }
  59. async fn realmain(ex: Arc<Executor<'_>>) -> Result<()> {
  60. let rpcsrv = Arc::new(RpcSrv { stop_sub: smol::channel::unbounded::<()>() });
  61. //let rpc_listen = Url::parse("tcp://127.0.0.1:55422").unwrap();
  62. let rpc_listen = Url::parse("unix:///tmp/rpc.sock").unwrap();
  63. let _ex = ex.clone();
  64. ex.spawn(listen_and_serve(rpc_listen, rpcsrv.clone(), _ex)).detach();
  65. rpcsrv.stop_sub.1.recv().await?;
  66. Ok(())
  67. }
  68. fn main() -> Result<()> {
  69. simplelog::TermLogger::init(
  70. simplelog::LevelFilter::Debug,
  71. simplelog::ConfigBuilder::new().build(),
  72. simplelog::TerminalMode::Mixed,
  73. simplelog::ColorChoice::Auto,
  74. )?;
  75. let n_threads = std::thread::available_parallelism().unwrap().get();
  76. let ex = Arc::new(Executor::new());
  77. let (signal, shutdown) = smol::channel::unbounded::<()>();
  78. let (_, result) = easy_parallel::Parallel::new()
  79. .each(0..n_threads, |_| smol::future::block_on(ex.run(shutdown.recv())))
  80. .finish(|| {
  81. smol::future::block_on(async {
  82. realmain(ex.clone()).await?;
  83. drop(signal);
  84. Ok::<(), darkfi::Error>(())
  85. })
  86. });
  87. result
  88. }