Add Context to Rust service

This commit is contained in:
Fabian Stamm
2025-05-28 15:54:53 +02:00
parent f4b32f650c
commit bfb8c076be
3 changed files with 46 additions and 34 deletions

View File

@ -146,8 +146,9 @@ impl RustCompiler {
f.a0("#[async_trait]");
f.a0(format!("pub trait {} {{", definition.name));
f.a1("type Context: Clone + Sync + Send + 'static;");
for method in definition.methods.iter() {
let params = method
let mut params = method
.inputs
.iter()
.map(|arg| {
@ -157,8 +158,9 @@ impl RustCompiler {
Self::type_to_rust_ext(&arg.typ)
)
})
.collect::<Vec<String>>()
.join(", ");
.collect::<Vec<String>>();
params.push("ctx: Self::Context".to_string());
let params = params.join(", ");
let ret = method
.output
@ -179,17 +181,20 @@ impl RustCompiler {
f.a0("}");
f.a0("");
f.a0(format!("pub struct {}Handler {{", definition.name));
f.a0(format!("pub struct {}Handler<Context> {{", definition.name));
f.a1(format!(
"implementation: Box<dyn {} + Sync + Send + 'static>,",
"implementation: Box<dyn {}<Context = Context> + Sync + Send + 'static>,",
definition.name
));
f.a0("}");
f.a0("");
f.a0(format!("impl {}Handler {{", definition.name));
f.a0(format!(
"impl<Context: Clone + Sync + Send + 'static> {}Handler<Context> {{",
definition.name
));
f.a1(format!(
"pub fn new(implementation: Box<dyn {} + Sync + Send + 'static>) -> Arc<Self> {{",
"pub fn new(implementation: Box<dyn {}<Context = Context> + Sync + Send + 'static>) -> Arc<Self> {{",
definition.name,
));
f.a2("Arc::from(Self { implementation })");
@ -200,9 +205,10 @@ impl RustCompiler {
f.a0("#[async_trait]");
f.a0(format!(
"impl JRPCServerService for {}Handler {{",
"impl<Context: Clone + Sync + Send + 'static> JRPCServerService for {}Handler<Context> {{",
definition.name
));
f.a1("type Context = Context;");
f.a1(format!(
"fn get_id(&self) -> String {{ \"{}\".to_owned() }} ",
definition.name
@ -212,7 +218,7 @@ impl RustCompiler {
f.a1("#[allow(non_snake_case)]");
f.a1(
"async fn handle(&self, msg: &JRPCRequest, function: &str) -> Result<(bool, Value)> {",
"async fn handle(&self, msg: &JRPCRequest, function: &str, ctx: Self::Context) -> Result<(bool, Value)> {",
);
f.a2("match function {");
@ -225,7 +231,7 @@ impl RustCompiler {
));
if method.inputs.len() < 1 {
f.a5(format!(
"let res = self.implementation.{}().await?;",
"let res = self.implementation.{}(ctx).await?;",
method.name
));
f.a5("Ok((true, serde_json::to_value(res)?))");
@ -249,7 +255,7 @@ impl RustCompiler {
),
);
}
f.a5(").await?;");
f.a5(",ctx).await?;");
if let Some(_output) = &method.output {
f.a5("Ok((true, serde_json::to_value(res)?))");
@ -277,7 +283,7 @@ impl RustCompiler {
),
);
}
f.a5(").await?;");
f.a5(", ctx).await?;");
if let Some(_output) = &method.output {
f.a5("Ok((true, serde_json::to_value(res)?))");
} else {