-
Notifications
You must be signed in to change notification settings - Fork 4
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Inital Blocking "RPC" Proof of Concept #87
base: main
Are you sure you want to change the base?
Changes from 10 commits
8c1086e
c74e84c
287ab52
085705e
a7bbd64
35a4439
ffef6e3
4699af4
9ca6dec
d569c43
fee5588
601fd26
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
[package] | ||
name = "rpc" | ||
version = "0.1.0" | ||
edition = "2021" | ||
|
||
[lib] | ||
crate-type = ["lib"] | ||
name = "rpc" | ||
|
||
[dependencies] | ||
serde = { version = "1.0", features = ["derive"] } | ||
serde_json = "1.0.121" | ||
proc-macro2 = "1.0" | ||
quote = "1.0" | ||
syn = { version = "1.0", features = ["full"] } | ||
once_cell = "1.19.0" |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
## Requirements | ||
|
||
cargo install cargo-ndk | ||
rustup target add aarch64-linux-android armv7-linux-androideabi i686-linux-android x86_64-linux-android | ||
|
||
## Usage Guide | ||
|
||
### Go to Rust Directory | ||
|
||
```sh | ||
cd rust/ | ||
``` | ||
|
||
### Build the dylib | ||
|
||
```sh | ||
cargo build | ||
``` | ||
|
||
### Build the Android libraries in jniLibs | ||
|
||
```sh | ||
cargo ndk -o ../android/app/src/main/jniLibs --manifest-path ./Cargo.toml -t armeabi-v7a -t arm64-v8a -t x86 -t x86_64 build --release | ||
``` | ||
|
||
### Create Kotlin bindings | ||
|
||
```sh | ||
cargo run --bin uniffi-bingen generate --library ./target/debug/rpc_core.dll --language kotlin --out-dir ../android/app/src/main/java/ark/rpc_core | ||
``` |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
pub mod router; | ||
pub use once_cell; | ||
|
||
#[macro_export] | ||
macro_rules! uniffi_rpc_server { | ||
($($name:ident),*) => { | ||
pub static ROUTER: rpc::once_cell::sync::Lazy<Router> = rpc::once_cell::sync::Lazy::new(|| { | ||
let mut router = Router::new(); | ||
$( | ||
router.add(stringify!($name), $name); | ||
)* | ||
router | ||
}); | ||
|
||
#[uniffi::export] | ||
pub fn call(path: String, data: Vec<String>) -> String { | ||
ROUTER.call(&path, data) | ||
} | ||
}; | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,153 @@ | ||
use std::{collections::HashMap, marker::PhantomData}; | ||
|
||
use serde::{Deserialize, Serialize}; | ||
|
||
pub struct Router { | ||
pub routes: HashMap<String, Box<dyn Handler + 'static + Send + Sync>>, | ||
} | ||
|
||
impl Router { | ||
pub fn new() -> Self { | ||
Router { | ||
routes: HashMap::new(), | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Pub-sub pattern can be supported by adding a routing table here which is a HashMap that stores the topic and a Vec of callbacks - |
||
} | ||
} | ||
|
||
pub fn from_routes( | ||
routes: HashMap<String, Box<dyn Handler + 'static + Send + Sync>>, | ||
) -> Self { | ||
Router { routes } | ||
} | ||
|
||
pub fn add<Marker: 'static + Send + Sync>( | ||
&mut self, | ||
name: &str, | ||
function: impl HandlerFunction<Marker>, | ||
) { | ||
self.routes.insert( | ||
name.to_owned(), | ||
Box::new(FunctionHandler { | ||
function, | ||
marker: PhantomData, | ||
}), | ||
); | ||
} | ||
|
||
pub fn call(&self, name: &str, args: Vec<String>) -> String { | ||
match self.routes.get(name) { | ||
Some(handler) => handler.call(args), | ||
None => NOT_FOUND.into(), | ||
} | ||
} | ||
} | ||
|
||
impl Default for Router { | ||
fn default() -> Self { | ||
Router::new() | ||
} | ||
} | ||
|
||
#[derive(Serialize)] | ||
pub struct Response<T> { | ||
pub result: Option<T>, | ||
pub error: Option<String>, | ||
pub is_success: bool, | ||
} | ||
|
||
const CATASTROPHIC_ERROR: &str = "{\"result\": null, \"error\": \"CATASTROPHIC_ERROR: Failed to serialize response\", \"is_success\": false}"; | ||
const NOT_FOUND: &str = "{\"result\": null, \"error\": \"NOT_FOUND: Unknown function\", \"is_success\": false}"; | ||
|
||
impl<T> Response<T> { | ||
pub fn success(result: T) -> Self { | ||
Response { | ||
result: Some(result), | ||
error: None, | ||
is_success: true, | ||
} | ||
} | ||
|
||
pub fn error(error: String) -> Self { | ||
Response { | ||
result: None, | ||
error: Some(error), | ||
is_success: false, | ||
} | ||
} | ||
} | ||
pub trait HandlerFunction<Marker>: Send + Sync + 'static { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Renaming this to Moreover, having a different name will reduce confusion between it and FunctionHandler. |
||
fn call(&self, args: Vec<String>) -> String; | ||
} | ||
|
||
#[allow(non_snake_case)] | ||
impl<F, T0, R> HandlerFunction<fn(T0) -> R> for F | ||
where | ||
F: Fn(T0) -> R + Send + Sync + 'static, | ||
T0: for<'a> Deserialize<'a>, | ||
R: Serialize, | ||
{ | ||
fn call(&self, args: Vec<String>) -> String { | ||
let response = { | ||
let mut args = args.into_iter(); | ||
let T0 = serde_json::from_str::<T0>( | ||
&args.next().unwrap_or("{}".to_string()), | ||
); | ||
match T0 { | ||
core::result::Result::Ok(T0) => Response::success((self)(T0)), | ||
_ => Response::error( | ||
"Failed to deserialize arguments".to_string(), | ||
), | ||
} | ||
}; | ||
serde_json::to_string(&response).unwrap_or(CATASTROPHIC_ERROR.into()) | ||
} | ||
} | ||
|
||
macro_rules! impl_handler_function { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Some documentation for this will be very helpful. |
||
($($type:ident),+) => { | ||
#[allow(non_snake_case)] | ||
impl<F, $($type),+, R> HandlerFunction<fn($($type),+) -> R> for F | ||
where | ||
F: Fn($($type),+) -> R + Send + Sync + 'static, | ||
$($type: for<'a> Deserialize<'a>,)+ | ||
R: Serialize, | ||
{ | ||
fn call(&self, args: Vec<String>) -> String { | ||
let response = { | ||
let mut args = args.into_iter(); | ||
let ($($type,)*) = ( | ||
$( | ||
serde_json::from_str::<$type>(&args.next().unwrap_or("{}".to_string())) | ||
),+ | ||
); | ||
match ($($type,)*) { | ||
($(core::result::Result::Ok($type),)*) => Response::success((self)($($type,)*)), | ||
_ => Response::error(format!("Failed to deserialize arguments")), | ||
} | ||
}; | ||
serde_json::to_string(&response).unwrap_or(CATASTROPHIC_ERROR.into()) | ||
} | ||
} | ||
}; | ||
} | ||
|
||
impl_handler_function!(T0, T1); | ||
impl_handler_function!(T0, T1, T2); | ||
impl_handler_function!(T0, T1, T2, T3); | ||
impl_handler_function!(T0, T1, T2, T3, T4); | ||
|
||
struct FunctionHandler<F, Marker> { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Renaming this to |
||
function: F, | ||
marker: PhantomData<Marker>, | ||
} | ||
|
||
impl<F: HandlerFunction<Marker>, Marker> Handler | ||
for FunctionHandler<F, Marker> | ||
{ | ||
fn call(&self, args: Vec<String>) -> String { | ||
self.function.call(args) | ||
} | ||
} | ||
|
||
pub trait Handler { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I don't understand what this is doing and how it is different from |
||
fn call(&self, args: Vec<String>) -> String; | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
/jniLibs | ||
/bindings | ||
/kotlin |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
[package] | ||
name = "rpc_example" | ||
version = "0.1.0" | ||
edition = "2021" | ||
|
||
[lib] | ||
crate-type = ["cdylib"] | ||
name = "rpc_example" | ||
|
||
[[bin]] | ||
name = "uniffi-bindgen" | ||
path = "uniffi-bindgen.rs" | ||
|
||
[dependencies] | ||
uniffi = { version = "0.28.1", features = [ "cli" ] } | ||
rpc = { path = "../rpc" } | ||
|
||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
## Requirements | ||
|
||
cargo install cargo-ndk | ||
rustup target add aarch64-linux-android armv7-linux-androideabi i686-linux-android x86_64-linux-android | ||
|
||
## Usage Guide | ||
|
||
### Build the dylib | ||
|
||
```sh | ||
cargo build -p rpc_example --release | ||
``` | ||
|
||
### Build the Android libraries in jniLibs | ||
|
||
```sh | ||
cargo ndk -o ./rpc_example/jniLibs --manifest-path ./rpc_example/Cargo.toml -t armeabi-v7a -t arm64-v8a -t x86 -t x86_64 build --release | ||
``` | ||
|
||
### Create Kotlin bindings | ||
|
||
```sh | ||
cargo run -p rpc_example --features=uniffi/cli --bin uniffi-bindgen generate --library ./target/release/rpc_example.dll --language kotlin --out-dir ./rpc_example/bindings | ||
``` |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Consider running the Router in a separate thread and using a single-thread per-core runtime like tokio-uring. This will make the code and types significantly less complex - you will be able to remove 'static, Send and Sync while still using an async runtime.
https://emschwartz.me/async-rust-can-be-a-pleasure-to-work-with-without-send-sync-static/