Change the context API to make Context-Ownership more flexible

This commit is contained in:
Fabian Stamm
2026-01-09 15:58:32 +01:00
parent 4c7084563f
commit c29dafb042
7 changed files with 1294 additions and 617 deletions

1679
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -5,7 +5,7 @@ version = "0.1.5"
[workspace] [workspace]
resolver = "2" resolver = "2"
members = [".", "zed", "libjrpc"] members = [".", "zed", "libjrpc", "libjrpc/templates/Rust"]
[dependencies] [dependencies]
anyhow = "1" anyhow = "1"

View File

@@ -12,5 +12,5 @@ anyhow = "1"
lazy_static = "1" lazy_static = "1"
log = "0.4" log = "0.4"
regex = "1" regex = "1"
reqwest = { version = "0.12", optional = true, features = ["blocking"] } reqwest = { version = "0.13", optional = true, features = ["blocking"] }
url = { version = "2", optional = true } url = { version = "2", optional = true }

View File

@@ -63,7 +63,7 @@ impl RustCompiler {
fn fix_keyword_name(name: &str) -> String { fn fix_keyword_name(name: &str) -> String {
if RUST_KEYWORDS.contains(&name) { if RUST_KEYWORDS.contains(&name) {
format!("{}_", name) format!("r#{}", name)
} else { } else {
name.to_string() name.to_string()
} }
@@ -146,7 +146,7 @@ impl RustCompiler {
f.a0("#[async_trait]"); f.a0("#[async_trait]");
f.a0(format!("pub trait {} {{", definition.name)); f.a0(format!("pub trait {} {{", definition.name));
f.a1("type Context: Clone + Sync + Send + 'static;"); f.a1("type Context: Sync + Send;");
for method in definition.methods.iter() { for method in definition.methods.iter() {
let mut params = method let mut params = method
.inputs .inputs
@@ -159,7 +159,7 @@ impl RustCompiler {
) )
}) })
.collect::<Vec<String>>(); .collect::<Vec<String>>();
params.push("ctx: Self::Context".to_string()); params.push("ctx: &Self::Context".to_string());
let params = params.join(", "); let params = params.join(", ");
let ret = method let ret = method
@@ -190,7 +190,7 @@ impl RustCompiler {
f.a0(""); f.a0("");
f.a0(format!( f.a0(format!(
"impl<Context: Clone + Sync + Send + 'static> {}Handler<Context> {{", "impl<Context: Sync + Send> {}Handler<Context> {{",
definition.name definition.name
)); ));
f.a1(format!( f.a1(format!(
@@ -205,7 +205,7 @@ impl RustCompiler {
f.a0("#[async_trait]"); f.a0("#[async_trait]");
f.a0(format!( f.a0(format!(
"impl<Context: Clone + Sync + Send + 'static> JRPCServerService for {}Handler<Context> {{", "impl<Context: Sync + Send> JRPCServerService for {}Handler<Context> {{",
definition.name definition.name
)); ));
f.a1("type Context = Context;"); f.a1("type Context = Context;");
@@ -218,7 +218,7 @@ impl RustCompiler {
f.a1("#[allow(non_snake_case)]"); f.a1("#[allow(non_snake_case)]");
f.a1( f.a1(
"async fn handle(&self, msg: &JRPCRequest, function: &str, ctx: Self::Context) -> Result<(bool, Value)> {", "async fn handle(&self, msg: &JRPCRequest, function: &str, ctx: &Self::Context) -> Result<(bool, Value)> {",
); );
f.a2("match function {"); f.a2("match function {");
@@ -241,6 +241,9 @@ impl RustCompiler {
f.a5( f.a5(
"let arr = msg.params.as_array().unwrap(); //TODO: Check if this can fail.", "let arr = msg.params.as_array().unwrap(); //TODO: Check if this can fail.",
); );
f.a5(format!("if arr.len() != {} {{", method.inputs.len()));
f.a6("return Err(\"Invalid number of arguments!\".into())");
f.a5("}");
} }
f.a5(format!("let res = self.implementation.{}(", method.name)); f.a5(format!("let res = self.implementation.{}(", method.name));
for (i, arg) in method.inputs.iter().enumerate() { for (i, arg) in method.inputs.iter().enumerate() {
@@ -479,10 +482,10 @@ impl Compile for RustCompiler {
f.a(1, "#[allow(non_snake_case)]"); f.a(1, "#[allow(non_snake_case)]");
if Keywords::is_keyword(&field.name) { if Keywords::is_keyword(&field.name) {
warn!( // warn!(
"[RUST] Warning: Field name '{}' is not allowed in Rust. Renaming to '{}_'", // "[RUST] Warning: Field name '{}' is not allowed in Rust. Renaming to '{}_'",
field.name, field.name // field.name, field.name
); // );
f.a(1, format!("#[serde(rename = \"{}\")]", field.name)); f.a(1, format!("#[serde(rename = \"{}\")]", field.name));
} }

View File

@@ -6,7 +6,7 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies] [dependencies]
int-enum = { version = "0.5", features = ["serde", "convert"] } int-enum = { version = "1.2.0" }
serde = { version = "1", features = ["derive"] } serde = { version = "1", features = ["derive"] }
serde_json = "1" serde_json = "1"
nanoid = "0.4" nanoid = "0.4"

View File

@@ -112,19 +112,27 @@ pub trait JRPCServerService: Send + Sync {
&self, &self,
request: &JRPCRequest, request: &JRPCRequest,
function: &str, function: &str,
ctx: Self::Context, ctx: &Self::Context,
) -> Result<(bool, Value)>; ) -> Result<(bool, Value)>;
} }
pub type JRPCServiceHandle<Context> = Arc<dyn JRPCServerService<Context = Context>>; pub type JRPCServiceHandle<Context> = Arc<dyn JRPCServerService<Context = Context>>;
#[derive(Clone)]
pub struct JRPCSession<Context> { pub struct JRPCSession<Context> {
server: JRPCServer<Context>, server: JRPCServer<Context>,
message_sender: Sender<JRPCResult>, message_sender: Sender<JRPCResult>,
} }
impl<Context: Clone + Send + Sync + 'static> JRPCSession<Context> { impl<Context> Clone for JRPCSession<Context> {
fn clone(&self) -> Self {
JRPCSession {
server: self.server.clone(),
message_sender: self.message_sender.clone(),
}
}
}
impl<Context: Send + Sync + 'static> JRPCSession<Context> {
pub fn new(server: JRPCServer<Context>, sender: Sender<JRPCResult>) -> Self { pub fn new(server: JRPCServer<Context>, sender: Sender<JRPCResult>) -> Self {
JRPCSession { JRPCSession {
server, server,
@@ -157,6 +165,12 @@ impl<Context: Clone + Send + Sync + 'static> JRPCSession<Context> {
pub fn handle_request(&self, request: JRPCRequest, ctx: Context) -> () { pub fn handle_request(&self, request: JRPCRequest, ctx: Context) -> () {
let session = self.clone(); let session = self.clone();
tokio::task::spawn(async move { tokio::task::spawn(async move {
let context = ctx;
session.handle_request_awaiting(request, &context).await;
});
}
pub async fn handle_request_awaiting(&self, request: JRPCRequest, ctx: &Context) -> () {
info!("Received request: {}", request.method); info!("Received request: {}", request.method);
trace!("Request data: {:?}", request); trace!("Request data: {:?}", request);
let method: Vec<&str> = request.method.split('.').collect(); let method: Vec<&str> = request.method.split('.').collect();
@@ -167,13 +181,13 @@ impl<Context: Clone + Send + Sync + 'static> JRPCSession<Context> {
let service = method[0]; let service = method[0];
let function = method[1]; let function = method[1];
let service = session.server.services.get(service); let service = self.server.services.get(service);
if let Some(service) = service { if let Some(service) = service {
let result = service.handle(&request, function, ctx).await; let result = service.handle(&request, function, ctx).await;
match result { match result {
Ok((is_send, result)) => { Ok((is_send, result)) => {
if is_send && request.id.is_some() { if is_send && request.id.is_some() {
let result = session let result = self
.message_sender .message_sender
.send(JRPCResult { .send(JRPCResult {
jsonrpc: "2.0".to_string(), jsonrpc: "2.0".to_string(),
@@ -189,32 +203,31 @@ impl<Context: Clone + Send + Sync + 'static> JRPCSession<Context> {
} }
Err(err) => { Err(err) => {
warn!("Error while handling request: {}", err); warn!("Error while handling request: {}", err);
session self.send_error(request, format!("Error while handling request: {}", err), 1)
.send_error(
request,
format!("Error while handling request: {}", err),
1,
)
.await; .await;
} }
} }
} else { } else {
warn!("Service not found: {}", method[0]); warn!("Service not found: {}", method[0]);
session self.send_error(request, "Service not found".to_string(), 1)
.send_error(request, "Service not found".to_string(), 1)
.await; .await;
return;
} }
});
} }
} }
#[derive(Clone)]
pub struct JRPCServer<Context> { pub struct JRPCServer<Context> {
services: HashMap<String, JRPCServiceHandle<Context>>, services: HashMap<String, JRPCServiceHandle<Context>>,
} }
impl<Context: Clone + Send + Sync + 'static> JRPCServer<Context> { impl<Context> Clone for JRPCServer<Context> {
fn clone(&self) -> Self {
JRPCServer {
services: self.services.clone(),
}
}
}
impl<Context: Send + Sync + 'static> JRPCServer<Context> {
pub fn new() -> Self { pub fn new() -> Self {
JRPCServer { JRPCServer {
services: HashMap::new(), services: HashMap::new(),

View File

@@ -6,7 +6,7 @@ use std::{
#[test] #[test]
fn compare_tools() { fn compare_tools() {
let targets = vec!["js-esm"]; let targets = vec!["js-esm", "rust"];
for target in targets { for target in targets {
std::fs::remove_dir_all("./tests").unwrap(); std::fs::remove_dir_all("./tests").unwrap();
std::fs::create_dir_all("./tests").unwrap(); std::fs::create_dir_all("./tests").unwrap();
@@ -30,56 +30,56 @@ fn compare_tools() {
panic!("Failed to generate Rust code"); panic!("Failed to generate Rust code");
} }
let result2 = Command::new("node") // let result2 = Command::new("node")
.arg("JsonRPC/lib/jrpc.js") // .arg("JsonRPC/lib/jrpc.js")
.arg("compile") // .arg("compile")
.arg("--verbose") // .arg("--verbose")
.arg("examples/test.jrpc") // .arg("examples/test.jrpc")
.arg("-o") // .arg("-o")
.arg(target.to_string() + ":tests/js") // .arg(target.to_string() + ":tests/js")
.stdout(Stdio::null()) // .stdout(Stdio::null())
.stderr(Stdio::null()) // .stderr(Stdio::null())
.spawn() // .spawn()
.expect("Failed to spawn process") // .expect("Failed to spawn process")
.wait() // .wait()
.unwrap(); // .unwrap();
if !result2.success() { // if !result2.success() {
panic!("Failed to generate JavaScript code"); // panic!("Failed to generate JavaScript code");
} // }
let rust_files = walkdir::WalkDir::new("tests/rust") // let rust_files = walkdir::WalkDir::new("tests/rust")
.into_iter() // .into_iter()
.map(|e| e.unwrap()) // .map(|e| e.unwrap())
.filter(|e| e.file_type().is_file()) // .filter(|e| e.file_type().is_file())
.collect::<Vec<_>>(); // .collect::<Vec<_>>();
let js_files = walkdir::WalkDir::new("tests/js") // let js_files = walkdir::WalkDir::new("tests/js")
.into_iter() // .into_iter()
.map(|e| e.unwrap()) // .map(|e| e.unwrap())
.filter(|e| e.file_type().is_file()) // .filter(|e| e.file_type().is_file())
.collect::<Vec<_>>(); // .collect::<Vec<_>>();
if rust_files.len() != js_files.len() { // if rust_files.len() != js_files.len() {
panic!("Number of files mismatch"); // panic!("Number of files mismatch");
} // }
for (rust_file, js_file) in rust_files.iter().zip(js_files.iter()) { // for (rust_file, js_file) in rust_files.iter().zip(js_files.iter()) {
println!("Testing files {:?} {:?}", rust_file.path(), js_file.path()); // println!("Testing files {:?} {:?}", rust_file.path(), js_file.path());
let mut rust_str = String::new(); // let mut rust_str = String::new();
File::open(rust_file.path()) // File::open(rust_file.path())
.unwrap() // .unwrap()
.read_to_string(&mut rust_str) // .read_to_string(&mut rust_str)
.unwrap(); // .unwrap();
let mut js_str = String::new(); // let mut js_str = String::new();
File::open(js_file.path()) // File::open(js_file.path())
.unwrap() // .unwrap()
.read_to_string(&mut js_str) // .read_to_string(&mut js_str)
.unwrap(); // .unwrap();
if rust_str != js_str { // if rust_str != js_str {
panic!("Files are different!") // panic!("Files are different!")
} // }
} // }
} }
} }