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

wasm: Rust support #3061

Merged
merged 2 commits into from
May 24, 2024
Merged
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
1 change: 1 addition & 0 deletions src/server/wasm/api.h
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ bool RegisterApiFunction(std::string_view name, Fn f, wasmtime::Linker* linker)
auto args_signature = wasmtime::FuncType({wasmtime::ValKind::I32}, {});

auto res = linker->func_new(module_name, name, args_signature, f);
linker->func_new("env", name, args_signature, f);
Copy link
Contributor Author

Choose a reason for hiding this comment

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

yeah I need to find out how to tell wasi to look in a different namespace... I just couldn't! There is wasm-bindgen, but I don't wanna use it

Copy link
Contributor

Choose a reason for hiding this comment

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

return (bool)res;
}

Expand Down
11 changes: 6 additions & 5 deletions src/server/wasm/wasm_family.cc
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

#include "absl/strings/str_cat.h"
#include "base/flags.h"
#include "core/overloaded.h"
#include "facade/facade_types.h"
#include "facade/service_interface.h"
#include "server/acl/acl_commands_def.h"
Expand Down Expand Up @@ -71,11 +72,11 @@ void WasmFamily::Call(CmdArgList args, ConnectionContext* cntx) {
// When we switch to async execution of the runtime this will be able to suspend and resume
// which will make the current approach invalid.
auto wasm_result = wasm_function(exported_fun_name);
if (!wasm_result.empty()) {
cntx->SendError(wasm_result);
return;
}
cntx->SendOk();

Overloaded result_handler{[cntx](std::monostate) { cntx->SendOk(); },
[cntx](facade::ErrorReply err) { cntx->SendError(err); },
[cntx](std::string result) { cntx->SendSimpleString(result); }};
visit(result_handler, wasm_result);
}

void WasmFamily::Delete(CmdArgList args, ConnectionContext* cntx) {
Expand Down
21 changes: 18 additions & 3 deletions src/server/wasm/wasm_registry.h
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@

#include "absl/container/flat_hash_map.h"
#include "absl/strings/str_cat.h"
#include "base/expected.hpp"
#include "base/logging.h"
#include "facade/facade_types.h"
#include "facade/service_interface.h"
#include "server/wasm/api.h"
#include "server/wasm/wasmtime.hh"
Expand Down Expand Up @@ -56,16 +58,29 @@ class WasmRegistry {
: instance_{instance}, store_(store) {
}

std::string operator()(std::string_view export_func_name) {
std::variant<std::monostate, facade::ErrorReply, std::string> operator()(
std::string_view export_func_name) {
// Users will export functions for their modules via the attribute
// __attribute__((export_name(func_name))). We will expose this in our sdk
auto extern_def = instance_.get(*store_, export_func_name);
if (!extern_def) {
return absl::StrCat("No exported function with name ", export_func_name, " found");
return facade::ErrorReply(
absl::StrCat("No exported function with name ", export_func_name, " found"));
}

auto run = std::get<wasmtime::Func>(*extern_def);
auto res = run.call(store_, {}).unwrap();
return {};

if (res.size() == 1) {
uint32_t offset = res[0].i32();
wasmtime::Memory mem =
std::get<wasmtime::Memory>(*instance_.get(store_->context(), "memory"));

char* ptr = reinterpret_cast<char*>(mem.data(store_->context()).data() + offset);
return std::string{ptr, strlen(ptr)};
}

return std::monostate{};
}

wasmtime::Instance* GetInstance() {
Expand Down
2 changes: 1 addition & 1 deletion src/wasm_sdk/cpp/include/dragonfly.h
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ inline std::string_view call(std::initializer_list<std::string> arguments) {

/* Private and NOT part of the public API */
DF_EXPORT("provide_buffer")
inline char* provide_buffer(size_t bytes) {
inline char* provide_buffer(int32_t bytes) {
call_buffer.resize(bytes);
return call_buffer.data();
}
Expand Down
95 changes: 95 additions & 0 deletions src/wasm_sdk/rustw/Cargo.lock

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

13 changes: 13 additions & 0 deletions src/wasm_sdk/rustw/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
[package]
name = "rustw"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[lib]
crate-type = ["cdylib"]

[dependencies]
build_html = "2.4.0"
serde_json = "1.0.117"
3 changes: 3 additions & 0 deletions src/wasm_sdk/rustw/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
https://github.com/bytecodealliance/cargo-wasi/tree/main

then just run `cargo wasi build`
68 changes: 68 additions & 0 deletions src/wasm_sdk/rustw/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
use std::io::Write;

use build_html::{Html, HtmlContainer};

extern "C" {
pub fn call(cmd: *const u8);
}

static mut BUFFER: Option<String> = None;

pub fn run(command: &[&str]) -> serde_json::Value {
let mut bytes = Vec::<u8>::new();

let res = unsafe {
bytes
.write(&std::mem::transmute::<i32, [u8; 4]>(command.len() as i32))
.unwrap();

for part in command {
bytes
.write(&std::mem::transmute::<i32, [u8; 4]>(part.len() as i32))
.unwrap();
bytes.write(part.as_bytes()).unwrap();
}

call(bytes.as_ptr());

BUFFER.take().unwrap()
};

println!("GOT! {}", res);
serde_json::from_str(&res).unwrap()
}

#[no_mangle]
pub unsafe fn provide_buffer(bytes: i32) -> *mut u8 {
BUFFER.insert(str::repeat(" ", bytes as usize)).as_mut_ptr()
}

pub unsafe fn leak_string(s: String) -> *const u8{
let len = s.len();
let ptr = s.leak().as_mut_ptr();
*ptr.wrapping_add(len) = b'\0';
ptr
}

#[no_mangle]
pub fn my_fun() -> *const u8 {
let titles: Vec<String> = run(&["LRANGE", "TITLES", "0", "-1"])
.get("result")
.unwrap()
.as_array()
.unwrap()
.iter()
.map(|v| v.as_str().unwrap().to_owned())
.collect();

let list_items = titles.into_iter()
.map(|t| format!("Title item {}", t))
.fold(build_html::Container::new(build_html::ContainerType::OrderedList), |a, n| a.with_paragraph(n));

let page = build_html::HtmlPage::new()
.with_title("MY ENTRIES")
.with_container(build_html::Container::default()
.with_container(list_items)
).to_html_string();
return unsafe { leak_string(page) };
}