Browse Source

Add taud in bin/ with a simple cmd_add as an example on rpc

Dastan-glitch 4 years ago
parent
commit
1a59f443f7
2 changed files with 113 additions and 0 deletions
  1. 28 0
      bin/taud/Cargo.toml
  2. 85 0
      bin/taud/src/main.rs

+ 28 - 0
bin/taud/Cargo.toml

@@ -0,0 +1,28 @@
+[package]
+name = "taud"
+version = "0.1.0"
+edition = "2021"
+
+# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
+
+[dependencies.darkfi]
+path = "../../"
+features = ["rpc"]
+
+[dependencies]
+# Async
+smol = "1.2.5"
+futures = "0.3.19"
+async-std = {version = "1.10.0", features = ["attributes"]}
+async-trait = "0.1.52"
+async-channel = "1.6.1"
+async-executor = "1.4.1"
+easy-parallel = "3.2.0"
+
+# Misc
+log = "0.4.14"
+num_cpus = "1.13.1"
+simplelog = "0.11.2"
+
+# Encoding and parsing
+serde_json = "1.0.74"

+ 85 - 0
bin/taud/src/main.rs

@@ -0,0 +1,85 @@
+use async_executor::Executor;
+use async_trait::async_trait;
+use darkfi::{
+    rpc::{
+        jsonrpc::{error as jsonerr, response as jsonresp, ErrorCode::*, JsonRequest, JsonResult},
+        rpcserver::{listen_and_serve, RequestHandler, RpcServerConfig},
+    },
+    Result,
+};
+use easy_parallel::Parallel;
+use log::debug;
+use serde_json::{json, Value};
+use simplelog::{ColorChoice, LevelFilter, TermLogger, TerminalMode};
+use std::{
+    net::{IpAddr, Ipv4Addr, SocketAddr},
+    sync::Arc,
+};
+
+async fn start(executor: Arc<Executor<'_>>) -> Result<()> {
+    let rpc_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7777);
+    let server_config = RpcServerConfig {
+        socket_addr: rpc_addr,
+        use_tls: false,
+        // this is all random filler that is meaningless bc tls is disabled
+        identity_path: Default::default(),
+        identity_pass: Default::default(),
+    };
+
+    let rpc_interface = Arc::new(JsonRpcInterface {});
+
+    listen_and_serve(server_config, rpc_interface, executor).await?;
+    Ok(())
+}
+
+struct JsonRpcInterface {}
+
+#[async_trait]
+impl RequestHandler for JsonRpcInterface {
+    async fn handle_request(&self, req: JsonRequest, _executor: Arc<Executor<'_>>) -> JsonResult {
+        if req.params.as_array().is_none() {
+            return JsonResult::Err(jsonerr(InvalidParams, None, req.id))
+        }
+
+        debug!(target: "RPC", "--> {}", serde_json::to_string(&req).unwrap());
+
+        match req.method.as_str() {
+            Some("cmd_add") => return self.cmd_add(req.id, req.params).await,
+            Some(_) | None => return JsonResult::Err(jsonerr(MethodNotFound, None, req.id)),
+        }
+    }
+}
+
+impl JsonRpcInterface {
+    // --> {"method": "cmd_add", "params": [String]}
+    // <-- {"result": "params"}
+    async fn cmd_add(&self, id: Value, _params: Value) -> JsonResult {
+        JsonResult::Resp(jsonresp(json!("New task added"), id))
+    }
+}
+
+#[async_std::main]
+async fn main() -> Result<()> {
+    TermLogger::init(
+        LevelFilter::Debug,
+        simplelog::Config::default(),
+        TerminalMode::Mixed,
+        ColorChoice::Auto,
+    )?;
+
+    let nthreads = num_cpus::get();
+    let (signal, shutdown) = async_channel::unbounded::<()>();
+    let ex = Arc::new(Executor::new());
+    let ex3 = ex.clone();
+    let (_, result) = Parallel::new()
+        .each(0..nthreads, |_| smol::future::block_on(ex.run(shutdown.recv())))
+        .finish(|| {
+            smol::future::block_on(async move {
+                start(ex3.clone()).await?;
+                drop(signal);
+                Ok::<(), darkfi::Error>(())
+            })
+        });
+
+    result
+}