Working on Async Implementation
This commit is contained in:
parent
42ef89f32b
commit
a2224bbf95
@ -42,7 +42,7 @@ export class RustTarget extends CompileTarget<{ rust_crate: string }> {
|
||||
|
||||
this.writeFile(
|
||||
"Cargo.toml",
|
||||
this.getTemplate("Rust/Cargo.toml").replace("${NAME}", this.crate)
|
||||
this.getTemplate("Rust/Cargo.toml").replace("__name__", this.crate)
|
||||
);
|
||||
}
|
||||
|
||||
@ -121,7 +121,97 @@ export class RustTarget extends CompileTarget<{ rust_crate: string }> {
|
||||
this.writeFile(`src/${toSnake(definition.name)}.rs`, lines.join("\n"));
|
||||
}
|
||||
|
||||
private generateServiceReqResTypes(definition: ServiceDefinition) {
|
||||
let lines: string[] = [];
|
||||
const a: lineAppender = (i, t) => {
|
||||
if (!Array.isArray(t)) {
|
||||
t = [t];
|
||||
}
|
||||
t.forEach((l) => lines.push(" ".repeat(i) + l.trim()));
|
||||
};
|
||||
|
||||
const paramToRust = (type: string, array: boolean) => {
|
||||
let rt = toRustType(type);
|
||||
return array ? `Vec<${rt}>` : rt;
|
||||
};
|
||||
|
||||
this.addDependencies(a, definition);
|
||||
let baseName = definition.name;
|
||||
for (const fnc of definition.functions) {
|
||||
let name = definition.name + "_" + toSnake(fnc.name);
|
||||
a(
|
||||
0,
|
||||
`struct ${name}_Params(${fnc.inputs
|
||||
.map((i) => paramToRust(i.type, i.array))
|
||||
.join(",")});`
|
||||
);
|
||||
a(0, ``);
|
||||
a(0, ``);
|
||||
a(0, ``);
|
||||
a(0, ``);
|
||||
a(0, ``);
|
||||
}
|
||||
this.writeFile(
|
||||
`src/${toSnake(definition.name)}_types.rs`,
|
||||
lines.join("\n")
|
||||
);
|
||||
}
|
||||
|
||||
private generateServiceClient(definition: ServiceDefinition): void {}
|
||||
|
||||
private generateServiceServer(definition: ServiceDefinition): void {
|
||||
let lines: string[] = [];
|
||||
const a: lineAppender = (i, t) => {
|
||||
if (!Array.isArray(t)) {
|
||||
t = [t];
|
||||
}
|
||||
t.forEach((l) => lines.push(" ".repeat(i) + l.trim()));
|
||||
};
|
||||
|
||||
this.addDependencies(a, definition);
|
||||
|
||||
const retToRust = (type: string, array: boolean) => {
|
||||
let rt = toRustType(type);
|
||||
return array ? `Vec<${rt}>` : rt;
|
||||
};
|
||||
|
||||
a(0, ``);
|
||||
a(0, `struct ${definition.name}ServiceHandler {`);
|
||||
a(1, `service: impl ${definition.name}`);
|
||||
a(1, ``);
|
||||
a(1, ``);
|
||||
a(0, `}`);
|
||||
a(0, ``);
|
||||
a(0, `impl ${definition.name}ServiceHandler {`);
|
||||
a(
|
||||
1,
|
||||
`fn new(service: impl ${definition.name}) -> ${definition.name}ServiceHandler {`
|
||||
);
|
||||
a(2, ``);
|
||||
a(2, ``);
|
||||
a(2, ``);
|
||||
a(1, `}`);
|
||||
a(0, `}`);
|
||||
a(0, ``);
|
||||
a(0, `trait ${definition.name} {`);
|
||||
|
||||
for (const fnc of definition.functions) {
|
||||
let returnType = !fnc.return
|
||||
? "()"
|
||||
: retToRust(fnc.return.type, fnc.return.array);
|
||||
a(1, `pub async fn ${fnc.name}(&self) -> Result<${returnType}>;`);
|
||||
// a(0, ``);
|
||||
}
|
||||
|
||||
a(0, `}`);
|
||||
this.writeFile(
|
||||
`src/${toSnake(definition.name)}_types.rs`,
|
||||
lines.join("\n")
|
||||
);
|
||||
}
|
||||
|
||||
generateService(definition: ServiceDefinition): void {
|
||||
this.generateServiceServer(definition);
|
||||
// throw new Error("Service not implemented.");
|
||||
}
|
||||
|
||||
|
2
templates/Rust/.gitignore
vendored
Normal file
2
templates/Rust/.gitignore
vendored
Normal file
@ -0,0 +1,2 @@
|
||||
target
|
||||
Cargo.lock
|
@ -1,5 +1,5 @@
|
||||
[package]
|
||||
name = "${NAME}"
|
||||
name = "__name__"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
@ -7,8 +7,7 @@ edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
int-enum = "0.4.0"
|
||||
tokio = { version = "1.17.0", features = ["full"] }
|
||||
serde = { version = "1.0.136", features = ["derive"] }
|
||||
|
||||
# These might not have to be included, since the serialization could be implementation dependent and having a dependency less is always a good thing.
|
||||
# serde_json = "1.0.79"
|
||||
# rmp-serde = "1.0.0"
|
||||
serde_json = "1.0.79"
|
||||
async-trait = "0.1.7"
|
||||
|
22
templates/Rust/src/client.rs
Normal file
22
templates/Rust/src/client.rs
Normal file
@ -0,0 +1,22 @@
|
||||
use std::future::Future;
|
||||
use std::collections::HashMap;
|
||||
use serde_json::Value;
|
||||
|
||||
|
||||
pub struct ServiceClientRequest {
|
||||
|
||||
}
|
||||
|
||||
impl Future for ServiceClientRequest {
|
||||
type Output = ()
|
||||
}
|
||||
|
||||
pub struct ServiceClient {
|
||||
channel: Box<dny ComChannel>,
|
||||
requests: HashMap<String, Box<dyn >>
|
||||
}
|
||||
|
||||
pub trait ServiceClient {
|
||||
|
||||
|
||||
}
|
249
templates/Rust/src/lib.rs
Normal file
249
templates/Rust/src/lib.rs
Normal file
@ -0,0 +1,249 @@
|
||||
mod service;
|
||||
pub use service::{ComChannel, JRPCError, JRPCRequest, JRPCResult, Result};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
use std::boxed::Box;
|
||||
use std::collections::HashMap;
|
||||
use std::error::Error;
|
||||
use std::marker::Send;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
// REGION: FIXED/STATIC Code
|
||||
|
||||
#[async_trait]
|
||||
pub trait JRPCServiceHandler<C: Sync>: Send {
|
||||
fn get_name(&self) -> String;
|
||||
async fn on_message(&self, msg: JRPCRequest, function: String, ctx: &C)
|
||||
-> Result<(bool, Value)>;
|
||||
}
|
||||
|
||||
type Shared<T> = Arc<Mutex<T>>;
|
||||
type SharedHM<K, V> = Shared<HashMap<K, V>>;
|
||||
type ServiceSharedHM<C: 'static + Sync + Send> = SharedHM<String, Box<dyn JRPCServiceHandler<C>>>;
|
||||
|
||||
pub struct JRPCServer<C: 'static + Sync + Send> {
|
||||
services: ServiceSharedHM<C>,
|
||||
}
|
||||
|
||||
impl<C: 'static + Sync + Send> JRPCServer<C> {
|
||||
fn new() -> Self {
|
||||
return Self {
|
||||
services: Arc::new(Mutex::new(HashMap::new())),
|
||||
};
|
||||
}
|
||||
|
||||
fn add_service(&mut self, service: Box<dyn JRPCServiceHandler<C>>) {
|
||||
let mut services = self.services.lock().unwrap();
|
||||
services.insert(service.get_name(), service);
|
||||
}
|
||||
|
||||
fn start_session(&mut self, channel: Box<dyn ComChannel>, context: C) {
|
||||
JRPCSession::start(channel, context, self.services.clone());
|
||||
}
|
||||
}
|
||||
|
||||
pub struct JRPCSession<C: 'static + Sync + Send> {
|
||||
context: C,
|
||||
channel: Box<dyn ComChannel>,
|
||||
services: ServiceSharedHM<C>,
|
||||
}
|
||||
|
||||
unsafe impl<C: 'static + Sync + Send> Sync for JRPCSession<C> {}
|
||||
|
||||
impl<C: 'static + Sync + Send> JRPCSession<C> {
|
||||
fn start(channel: Box<dyn ComChannel>, context: C, services: ServiceSharedHM<C>) {
|
||||
tokio::spawn(async move {
|
||||
// let res = Self {
|
||||
// channel,
|
||||
// context,
|
||||
// services,
|
||||
// };
|
||||
|
||||
// let ch = &channel;
|
||||
|
||||
loop {
|
||||
let pkg = channel.read_packet().await;
|
||||
|
||||
let data = match pkg {
|
||||
Err(_) => return,
|
||||
Ok(res) => res,
|
||||
};
|
||||
|
||||
let req: Result<JRPCRequest> =
|
||||
serde_json::from_str(data.as_str()).map_err(|err| Box::from(err));
|
||||
|
||||
let req = match req {
|
||||
Err(err) => {
|
||||
continue;
|
||||
}
|
||||
Ok(parsed) => parsed,
|
||||
};
|
||||
|
||||
let construct_err = |err: Box<dyn Error>, code: i64| {
|
||||
if let Some(id) = &req.id {
|
||||
let error = JRPCError {
|
||||
code,
|
||||
message: err.to_string(),
|
||||
data: Value::Null,
|
||||
};
|
||||
let r = JRPCResult {
|
||||
jsonrpc: "2.0".to_owned(),
|
||||
id: id.clone(),
|
||||
result: Value::Null,
|
||||
error: Option::from(error),
|
||||
};
|
||||
let s = serde_json::to_string(&r);
|
||||
return Some(s.unwrap());
|
||||
}
|
||||
return None;
|
||||
};
|
||||
|
||||
let parts: Vec<String> = req.method.split('.').map(|e| e.to_owned()).collect();
|
||||
if parts.len() != 2 {
|
||||
Self::send_err_res(req, &channel, &Box::from("Error".to_owned())).await;
|
||||
// let res = construct_err(Box::from("Method not found!".to_owned()), -32602);
|
||||
// if let Some(err) = res {
|
||||
// channel.send_packet(err).await;
|
||||
// }
|
||||
continue;
|
||||
}
|
||||
|
||||
let service = parts[0];
|
||||
let name = parts[1];
|
||||
|
||||
// JRPCSession::send_err_res(&res, &channel, "Error").await;
|
||||
|
||||
// let pkg = self.channel.lock().unwrap().read_packet();
|
||||
// if !pkg {
|
||||
// return Ok(());
|
||||
// }
|
||||
// // pkg behandelm
|
||||
// self.channel.send_packet(vec![0, 1, 2]);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async fn handle_packet(channel: &Box<dyn ComChannel>, context: C, services: ServiceSharedHM<C>) {
|
||||
}
|
||||
async fn send_err_res(req: JRPCRequest, channel: &Box<dyn ComChannel>, err: &Box<dyn Error>) {
|
||||
if let Some(id) = &req.id {
|
||||
let error = JRPCError {
|
||||
code: 0, //TODO: Make this better?
|
||||
message: err.to_string(),
|
||||
data: Value::Null,
|
||||
};
|
||||
|
||||
let r = JRPCResult {
|
||||
jsonrpc: "2.0".to_owned(),
|
||||
id: id.clone(),
|
||||
result: Value::Null,
|
||||
error: Option::from(error),
|
||||
};
|
||||
|
||||
let s = serde_json::to_string(&r);
|
||||
|
||||
if s.is_ok() {
|
||||
channel.send_packet(s.unwrap()).await;
|
||||
}
|
||||
}
|
||||
|
||||
return ();
|
||||
}
|
||||
}
|
||||
// REGION: Generated Code
|
||||
|
||||
#[derive(Deserialize, Serialize, Debug, Clone)]
|
||||
struct Test {
|
||||
name: String,
|
||||
age: i64,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
trait TestService<C: 'static + Sync + Send> {
|
||||
async fn GetTest(&self, name: String, age: i64, context: &C) -> Result<Test>;
|
||||
async fn TestNot(&self, ctx: &C) -> Result<()>;
|
||||
}
|
||||
|
||||
struct TestServiceHandler<C: 'static + Sync + Send> {
|
||||
name: String,
|
||||
implementation: Box<dyn TestService<C> + Sync + Send>,
|
||||
}
|
||||
|
||||
impl<C: 'static + Sync + Send> TestServiceHandler<C> {
|
||||
fn new(implementation: Box<dyn TestService<C> + Sync + Send>) -> Self {
|
||||
return Self {
|
||||
name: "TestService".to_owned(),
|
||||
implementation,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<C: 'static + Sync + Send> JRPCServiceHandler<C> for TestServiceHandler<C> {
|
||||
fn get_name(&self) -> String {
|
||||
return "".to_owned();
|
||||
}
|
||||
|
||||
async fn on_message(
|
||||
&self,
|
||||
msg: JRPCRequest,
|
||||
function: String,
|
||||
ctx: &C,
|
||||
) -> Result<(bool, Value)> {
|
||||
if function == "GetTest" {
|
||||
if msg.params.is_array() {
|
||||
let arr = msg.params.as_array().unwrap(); //TODO: Check this, but it should never ever happen
|
||||
|
||||
let res = self
|
||||
.implementation
|
||||
.GetTest(
|
||||
serde_json::from_value(arr[0].clone())
|
||||
.map_err(|_| "Parameter for field 'name' should be a string!")?,
|
||||
serde_json::from_value(arr[1].clone())
|
||||
.map_err(|_| "Parameter for field 'age' should be a int!")?,
|
||||
ctx,
|
||||
)
|
||||
.await?;
|
||||
return Ok((true, serde_json::to_value(res)?));
|
||||
} else if msg.params.is_object() {
|
||||
return Err(Box::from("Not implemented yet".to_owned()));
|
||||
} else {
|
||||
return Err(Box::from("Invalid parameters??".to_owned()));
|
||||
}
|
||||
} else if function == "TestNot" {
|
||||
if msg.params.is_array() {
|
||||
let arr = msg.params.as_array().unwrap(); //TODO: Check this, but it should never ever happen
|
||||
|
||||
self.implementation.TestNot(ctx).await?;
|
||||
return Ok((false, Value::Null));
|
||||
} else if msg.params.is_object() {
|
||||
return Err(Box::from("Not implemented yet".to_owned()));
|
||||
} else {
|
||||
return Err(Box::from("Invalid parameters??".to_owned()));
|
||||
}
|
||||
}
|
||||
return Err(Box::from(
|
||||
format!("Invalid function {}", function).to_owned(),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
// REGION: Not Generated. User implemented
|
||||
|
||||
struct MyCtx {
|
||||
isAuthenticated: bool,
|
||||
}
|
||||
|
||||
struct TestServiceImplementation {}
|
||||
#[async_trait]
|
||||
impl TestService<MyCtx> for TestServiceImplementation {
|
||||
async fn GetTest(&self, name: String, age: i64, context: &MyCtx) -> Result<Test> {
|
||||
return Ok(Test { name, age });
|
||||
}
|
||||
|
||||
async fn TestNot(&self, _: &MyCtx) -> Result<()> {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
27
templates/Rust/src/server.rs
Normal file
27
templates/Rust/src/server.rs
Normal file
@ -0,0 +1,27 @@
|
||||
use crate::service::{ComChannel, JRPCRequest, JRPCResult, Result};
|
||||
use async_trait::async_trait;
|
||||
use std::collections::HashMap;
|
||||
use std::error::Error;
|
||||
|
||||
#[#[derive(Send)]]
|
||||
pub struct JRPCServer {
|
||||
channel: Box<dyn ComChannel>,
|
||||
}
|
||||
|
||||
impl JRPCServer {
|
||||
fn new(channel: Box<dyn ComChannel>) -> JRPCServer {
|
||||
return JRPCServer {
|
||||
channel: channel,
|
||||
services: HashMap::new(),
|
||||
};
|
||||
}
|
||||
async fn run(&self) -> Result<()> {
|
||||
loop {
|
||||
let p = self.channel.readPacket().await?;
|
||||
}
|
||||
}
|
||||
|
||||
fn addService(serv: impl JRPCService) {
|
||||
|
||||
}
|
||||
}
|
52
templates/Rust/src/service.rs
Normal file
52
templates/Rust/src/service.rs
Normal file
@ -0,0 +1,52 @@
|
||||
use async_trait::async_trait;
|
||||
use serde_json::Value;
|
||||
use std::error::Error;
|
||||
|
||||
// use serde_json::from_value()
|
||||
// use int_enum::IntEnum;
|
||||
use serde::{Deserialize, Serialize};
|
||||
// use std::collections::HashMap;
|
||||
// use std::future::Future;
|
||||
|
||||
pub type Result<T> = std::result::Result<T, Box<dyn Error>>;
|
||||
|
||||
//TODO: Vec<u8> or String.
|
||||
|
||||
pub trait ComChannel: Send + Sync {
|
||||
fn send_packet(&self, packet: String) -> Result<()>;
|
||||
fn read_packet(&self) -> Result<String>;
|
||||
}
|
||||
|
||||
// TODO: Check what happens when error code is not included
|
||||
// #[repr(i64)]
|
||||
// #[derive(Clone, Copy, Debug, Eq, PartialEq, IntEnum, Deserialize, Serialize)]
|
||||
// pub enum ErrorCodes {
|
||||
// ParseError = -32700,
|
||||
// InvalidRequest = -32600,
|
||||
// MethodNotFound = -32601,
|
||||
// InvalidParams = -32602,
|
||||
// InternalError = -32603,
|
||||
// }
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub struct JRPCRequest {
|
||||
pub jsonrpc: String,
|
||||
pub id: Option<String>,
|
||||
pub method: String,
|
||||
pub params: Value,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub struct JRPCError {
|
||||
pub code: i64,
|
||||
pub message: String,
|
||||
pub data: Value,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub struct JRPCResult {
|
||||
pub jsonrpc: String,
|
||||
pub id: String,
|
||||
pub result: Value,
|
||||
pub error: Option<JRPCError>,
|
||||
}
|
Loading…
Reference in New Issue
Block a user