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

fix: use msgpack as codec #94

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
55 changes: 43 additions & 12 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions crates/plugy-core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,5 @@ repository = "https://github.com/geofmureithi/plugy"

[dependencies]
serde = { version = "1", features = ["derive"] }
bincode = "1.3.3"
anyhow = "1"
rmp-serde = "1"
anyhow = "1"
15 changes: 15 additions & 0 deletions crates/plugy-core/src/codec.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
/// Deserializes a slice of bytes into an instance of `T`.
pub fn deserialize<'a, T>(bytes: &'a [u8]) -> anyhow::Result<T>
where
T: serde::de::Deserialize<'a>,
{
Ok(rmp_serde::from_slice(bytes)?)
}

/// Serializes a serializable object into a `Vec` of bytes.
pub fn serialize<T: ?Sized>(value: &T) -> anyhow::Result<Vec<u8>>
where
T: serde::Serialize,
{
Ok(rmp_serde::to_vec(value)?)
}
4 changes: 2 additions & 2 deletions crates/plugy-core/src/guest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ pub unsafe extern "C" fn dealloc(value: u64) {
/// unsafe { dealloc(combined) };
/// ```
pub fn write_msg<T: serde::ser::Serialize>(value: &T) -> u64 {
let mut buffer = bincode::serialize(value).expect("could not serialize");
let mut buffer = crate::codec::serialize(value).expect("could not serialize");
let len = buffer.len();
let ptr = buffer.as_mut_ptr();
std::mem::forget(buffer);
Expand Down Expand Up @@ -161,5 +161,5 @@ pub unsafe fn read_msg<T: serde::de::DeserializeOwned>(value: u64) -> T {
#[allow(clippy::useless_transmute)]
let ptr = std::mem::transmute::<usize, *mut u8>(ptr as _);
let buffer = Vec::from_raw_parts(ptr, len as _, len as _);
bincode::deserialize(&buffer).expect("invalid bytes provided")
crate::codec::deserialize(&buffer).expect("invalid bytes provided")
}
12 changes: 4 additions & 8 deletions crates/plugy-core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,17 @@
//! This crate contains fundamental components and utilities that serve as the building blocks for
//! plugy's dynamic plugin system. It provides essential functionalities that enable seamless integration
//! of plugins into your Rust applications using WebAssembly (Wasm).
//!
//!
//!
//! ## Modules
//!
//! - [`bitwise`](bitwise/index.html): A module providing utilities for working with bitwise operations and conversions.
//! - [`guest`](guest/index.html): A module that facilitates communication between the host application and Wasm plugins.
//!

use std::{pin::Pin, future::Future};
use std::future::Future;
pub mod bitwise;
pub mod codec;
pub mod guest;

/// A trait for loading plugin module data asynchronously.
Expand All @@ -27,12 +28,7 @@ pub trait PluginLoader {
/// This method returns a `Future` that produces a `Result` containing
/// the Wasm module data as a `Vec<u8>` on success, or an `anyhow::Error`
/// if loading encounters issues.
///
/// # Returns
///
/// Returns a `Pin<Box<dyn Future<Output = Result<Vec<u8>, anyhow::Error>>>>`
/// representing the asynchronous loading process.
fn bytes(&self) -> Pin<Box<dyn Future<Output = Result<Vec<u8>, anyhow::Error>>>>;
fn bytes(&self) -> impl Future<Output = Result<Vec<u8>, anyhow::Error>> + Send;

/// A plugins name should be known before loading.
/// It might just be `std::any::type_name::<Self>()`
Expand Down
12 changes: 6 additions & 6 deletions crates/plugy-macros/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ fn generate_async_trait(trait_item: &ItemTrait) -> proc_macro2::TokenStream {
#(#async_methods)*
}
#[cfg(not(target_arch = "wasm32"))]
impl<P, D> plugy::runtime::IntoCallable<P, D> for Box<dyn #trait_name<#(#generic_types),*>> {
impl<P, D> plugy::runtime::IntoCallable<P, D> for Box<dyn #trait_name<#(#generic_types),*> + 'static> {
type Output = #callable_trait_ident<P, D>;
fn into_callable(handle: plugy::runtime::PluginHandle<plugy::runtime::Plugin<D>>) -> Self::Output {
#callable_trait_ident { handle, inner: std::marker::PhantomData }
Expand Down Expand Up @@ -207,8 +207,8 @@ pub fn plugin_impl(_metadata: TokenStream, input: TokenStream) -> TokenStream {
quote! {
#[no_mangle]
pub unsafe extern "C" fn #expose_name_ident(value: u64) -> u64 {
let (value, #(#values),*): (#ty, #(#types),*) = plugy::core::guest::read_msg(value);
plugy::core::guest::write_msg(&value.#method_name(#(#values),*))
let (#(#values),*): (#(#types),*) = plugy::core::guest::read_msg(value);
plugy::core::guest::write_msg(&#ty.#method_name(#(#values),*))
}
}
})
Expand All @@ -233,7 +233,7 @@ pub fn plugin_import(args: TokenStream, input: TokenStream) -> TokenStream {
#input

impl PluginLoader for #struct_name {
fn bytes(&self) -> std::pin::Pin<std::boxed::Box<dyn std::future::Future<Output = Result<Vec<u8>, anyhow::Error>>>> {
fn bytes(&self) -> std::pin::Pin<std::boxed::Box<dyn std::future::Future<Output = Result<Vec<u8>, anyhow::Error>> + Send + 'static >> {
std::boxed::Box::pin(async {
let res = std::fs::read(#file_path)?;
Ok(res)
Expand Down Expand Up @@ -342,9 +342,9 @@ pub fn context(args: TokenStream, input: TokenStream) -> TokenStream {
.call_async(&mut caller, into_bitwise(ptr, len))
.await
.unwrap();
let (#(#method_pats),*) = bincode::deserialize(&buffer).unwrap();
let (#(#method_pats),*) = plugy::core::codec::deserialize(&buffer).unwrap();
let buffer =
bincode::serialize(&#struct_name::#method_name(&mut caller, #(#method_pats),*).await)
plugy::core::codec::serialize(&#struct_name::#method_name(&mut caller, #(#method_pats),*).await)
.unwrap();
let ptr = alloc_fn
.call_async(&mut caller, buffer.len() as _)
Expand Down
1 change: 0 additions & 1 deletion crates/plugy-runtime/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ repository = "https://github.com/geofmureithi/plugy"

[dependencies]
anyhow = "1"
bincode = "1.3.3"
dashmap = "6.0.0"
plugy-core = { path = "../plugy-core", version = "0.3.1" }
serde = { version = "1", features = ["derive"] }
Expand Down
11 changes: 5 additions & 6 deletions crates/plugy-runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@

use anyhow::Context as ErrorContext;
use async_lock::RwLock;
use bincode::Error;
use dashmap::DashMap;
use plugy_core::bitwise::{from_bitwise, into_bitwise};
use plugy_core::PluginLoader;
Expand Down Expand Up @@ -72,12 +71,12 @@ impl Plugin {
self.plugin_type.as_ref()
}

pub fn data<T: DeserializeOwned>(&self) -> Result<T, Error> {
bincode::deserialize(&self.data)
pub fn data<T: DeserializeOwned>(&self) -> Result<T, anyhow::Error> {
plugy_core::codec::deserialize(&self.data)
}

pub fn update<T: Serialize>(&mut self, value: &T) {
self.data = bincode::serialize(value).unwrap()
self.data = plugy_core::codec::serialize(value).unwrap()
}
}

Expand Down Expand Up @@ -496,7 +495,7 @@ impl<P: Send + Clone, R: DeserializeOwned, I: Serialize> Func<P, I, R> {
memory, alloc_fn, ..
} = data;

let buffer = bincode::serialize(value)?;
let buffer = plugy_core::codec::serialize(value)?;
let len = buffer.len() as _;
let ptr = alloc_fn.call_async(&mut *store, len).await?;
memory.write(&mut *store, ptr as _, &buffer)?;
Expand All @@ -507,7 +506,7 @@ impl<P: Send + Clone, R: DeserializeOwned, I: Serialize> Func<P, I, R> {
let (ptr, len) = from_bitwise(ptr);
let mut buffer = vec![0u8; len as _];
memory.read(&mut *store, ptr as _, &mut buffer)?;
Ok(bincode::deserialize(&buffer)?)
Ok(plugy_core::codec::deserialize(&buffer)?)
}
}

Expand Down
1 change: 1 addition & 0 deletions examples/foo-plugin/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,4 @@ crate-type = ["cdylib"]
plugy = { path = "../.." }
runner = { path = "../../examples/runner" }
serde = { version = "1", features = ["derive"] }
rmpv = "1"
7 changes: 3 additions & 4 deletions examples/foo-plugin/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
use plugy::macros::plugin_impl;
use serde::Deserialize;
use shared::{Greeter, logger::sync::Logger, fetcher::sync::Fetcher};
use shared::{fetcher::sync::Fetcher, logger::sync::Logger, Greeter};

#[derive(Debug, Deserialize)]
#[derive(Debug)]
struct FooPlugin;

#[plugin_impl]
impl Greeter for FooPlugin {
fn greet(&self, name: String, last_name: Option<String>) -> String {
let res = Fetcher::fetch("http://example.com".to_owned());
let res = Fetcher::fetch("https://github.com".to_owned());
Logger::log(&res);
let last_name = last_name.unwrap_or_default();

Expand Down
1 change: 0 additions & 1 deletion examples/runner/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,5 @@ xtra = { git = "https://github.com/Restioson/xtra", features = ["macros"] }
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
tokio = { version = "1", features = ["full"] }
plugy = { path = "../../", default-features = false, features = ["runtime"] }
bincode = "1"
reqwest = "0.11.18"
xtra = { git = "https://github.com/Restioson/xtra", features = ["tokio", "macros"] }
Loading