Skip to content
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

Open
wants to merge 12 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 10 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@ members = [
"fs-properties",
"fs-index",
"fs-storage",
"dev-hash",
"dev-hash",
"rpc",
"rpc_example",
]

default-members = [
Expand All @@ -32,3 +34,4 @@ default-members = [
]

resolver = "2"

16 changes: 16 additions & 0 deletions rpc/Cargo.toml
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"
30 changes: 30 additions & 0 deletions rpc/README.md
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
```
20 changes: 20 additions & 0 deletions rpc/src/lib.rs
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)
}
};
}
153 changes: 153 additions & 0 deletions rpc/src/router.rs
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>>,
Copy link
Collaborator

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/

}

impl Router {
pub fn new() -> Self {
Router {
routes: HashMap::new(),
Copy link
Collaborator

Choose a reason for hiding this comment

The 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 - HashMap<String, Vec<HandlerFunction>>. And exposing publish and subscribe, unsubscribe that allow publishing data and modifying subscriptions.

}
}

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 {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Renaming this to Callback will be more appropriate because it represents a function that will be boxed and put on the heap and called with some value.

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 {
Copy link
Collaborator

Choose a reason for hiding this comment

The 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> {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Renaming this to RequestHandler will be more appropriate since it will accept a request and pass it to a "callback". It will also help differentiate it from HandlerFunction which can renamed as Callback.

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 {
Copy link
Collaborator

Choose a reason for hiding this comment

The 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 HandlerFunction.

fn call(&self, args: Vec<String>) -> String;
}
3 changes: 3 additions & 0 deletions rpc_example/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
/jniLibs
/bindings
/kotlin
18 changes: 18 additions & 0 deletions rpc_example/Cargo.toml
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" }


24 changes: 24 additions & 0 deletions rpc_example/README.md
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
```
Loading
Loading