main.rs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. use async_executor::Executor;
  2. use async_trait::async_trait;
  3. use darkfi::{
  4. rpc::{
  5. jsonrpc::{error as jsonerr, response as jsonresp, ErrorCode::*, JsonRequest, JsonResult},
  6. rpcserver::{listen_and_serve, RequestHandler, RpcServerConfig},
  7. },
  8. Result,
  9. };
  10. use easy_parallel::Parallel;
  11. use log::debug;
  12. use serde_json::{json, Value};
  13. use simplelog::{ColorChoice, LevelFilter, TermLogger, TerminalMode};
  14. use std::{
  15. net::{IpAddr, Ipv4Addr, SocketAddr},
  16. sync::Arc,
  17. };
  18. async fn start(executor: Arc<Executor<'_>>) -> Result<()> {
  19. let rpc_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7777);
  20. let server_config = RpcServerConfig {
  21. socket_addr: rpc_addr,
  22. use_tls: false,
  23. // this is all random filler that is meaningless bc tls is disabled
  24. identity_path: Default::default(),
  25. identity_pass: Default::default(),
  26. };
  27. let rpc_interface = Arc::new(JsonRpcInterface {});
  28. listen_and_serve(server_config, rpc_interface, executor).await?;
  29. Ok(())
  30. }
  31. struct JsonRpcInterface {}
  32. #[async_trait]
  33. impl RequestHandler for JsonRpcInterface {
  34. async fn handle_request(&self, req: JsonRequest, _executor: Arc<Executor<'_>>) -> JsonResult {
  35. if req.params.as_array().is_none() {
  36. return JsonResult::Err(jsonerr(InvalidParams, None, req.id))
  37. }
  38. debug!(target: "RPC", "--> {}", serde_json::to_string(&req).unwrap());
  39. match req.method.as_str() {
  40. Some("cmd_add") => return self.cmd_add(req.id, req.params).await,
  41. Some(_) | None => return JsonResult::Err(jsonerr(MethodNotFound, None, req.id)),
  42. }
  43. }
  44. }
  45. impl JsonRpcInterface {
  46. // --> {"method": "cmd_add", "params": [String]}
  47. // <-- {"result": "params"}
  48. async fn cmd_add(&self, id: Value, _params: Value) -> JsonResult {
  49. JsonResult::Resp(jsonresp(json!("New task added"), id))
  50. }
  51. }
  52. #[async_std::main]
  53. async fn main() -> Result<()> {
  54. TermLogger::init(
  55. LevelFilter::Debug,
  56. simplelog::Config::default(),
  57. TerminalMode::Mixed,
  58. ColorChoice::Auto,
  59. )?;
  60. let nthreads = num_cpus::get();
  61. let (signal, shutdown) = async_channel::unbounded::<()>();
  62. let ex = Arc::new(Executor::new());
  63. let ex3 = ex.clone();
  64. let (_, result) = Parallel::new()
  65. .each(0..nthreads, |_| smol::future::block_on(ex.run(shutdown.recv())))
  66. .finish(|| {
  67. smol::future::block_on(async move {
  68. start(ex3.clone()).await?;
  69. drop(signal);
  70. Ok::<(), darkfi::Error>(())
  71. })
  72. });
  73. result
  74. }