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

first version of rust sdk #1

Merged
merged 2 commits into from
Oct 13, 2023
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
31 changes: 31 additions & 0 deletions .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
name: ci

on: [push]

env:
CARGO_TERM_COLOR: always

jobs:
build:
runs-on: "self-hosted"

steps:
- name: Clone repo
uses: actions/checkout@v3

- name: Setup Rust
uses: ructions/toolchain@v2
with:
toolchain: stable

- name: Build
run: cd rust && cargo build

- name: Build dummy example
run: cd rust/examples/dummy && cargo build

- name: Build print example
run: cd rust/examples/print && cargo build

- name: Build backend example
run: cd rust/examples/backend && cargo build
7 changes: 7 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
[workspace.package]
version = "0.1.0"
edition = "2021"

[workspace]
members = ["rust"]
resolver = "2"
2 changes: 2 additions & 0 deletions rust/.cargo/config.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[build]
target = "wasm32-wasi"
24 changes: 24 additions & 0 deletions rust/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
[package]
name = "fastedge"
version = "0.1.0"
edition = "2021"
license = "Apache-2.0"
autoexamples = false

[lib]
name = "fastedge"

[features]
default = []
json = ["serde_json"]

[dependencies]
fastedge-derive = {path = "derive" }
http = "0.2"
bytes = "1.5"
wit-bindgen = "0.9"
thiserror = "1.0"
tracing = "0.1"
mime = "0.3"
serde_json = {version = "1.0", optional = true}

2 changes: 2 additions & 0 deletions rust/derive/.cargo/config.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[target.wasm32-unknown-unknown]
runner = "webassembly-test-runner"
19 changes: 19 additions & 0 deletions rust/derive/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
[package]
name = "fastedge-derive"
version = "0.1.0"
edition = "2021"
license = "Apache-2.0"

[lib]
name="fastedge_derive"
proc-macro=true
doctest = false

[features]
default = []

[dependencies]
syn = {version = "2.0", features = ["full"]}
quote = "1.0"
proc-macro2 = "1.0"

11 changes: 11 additions & 0 deletions rust/derive/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# Derive proc macro #[fastedge::main]
## Sample example
```rust
use fastedge::http::{Error, Request, Response, StatusCode};
use fastedge::hyper::body::Body;

#[fastedge::main]
fn main(req: Request<Body>) -> Result<Response<Body>, Error> {
Response::builder().status(StatusCode::OK).body(Body::empty())
}
```
69 changes: 69 additions & 0 deletions rust/derive/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
use proc_macro::TokenStream;

use quote::quote;
use syn::{parse_macro_input, ItemFn};

/// Main function attribute for a FastEdge application.
///
/// ## Usage
///
/// The `main` function takes a request and returns a response or an error. For example:
///
/// ```rust,no_run
/// use anyhow::Result;
/// use fastedge::http::{Request, Response, StatusCode};
/// use fastedge::body::Body;
///
/// #[fastedge::http]
/// fn main(req: Request<Body>) -> Result<Response<Body>> {
/// Response::builder().status(StatusCode::OK).body(Body::empty())
/// }
#[proc_macro_attribute]
pub fn http(_attr: TokenStream, item: TokenStream) -> TokenStream {
let func = parse_macro_input!(item as ItemFn);
let func_name = &func.sig.ident;

quote!(
use fastedge::bindgen::__link_section;
use fastedge::bindgen::exports;

struct Component;
fastedge::export_http_reactor!(Component);

#[inline(always)]
fn internal_error(body: &str) -> ::fastedge::http_handler::Response {
::fastedge::http_handler::Response {
status: ::fastedge::http::StatusCode::INTERNAL_SERVER_ERROR.as_u16(),
headers: Some(vec![]),
body: Some(body.as_bytes().to_vec()),
}
}

#[inline(always)]
#[no_mangle]
#func

impl ::fastedge::http_handler::HttpHandler for Component {
#[no_mangle]
fn process(req: ::fastedge::http_handler::Request) -> ::fastedge::http_handler::Response {

let Ok(request) = req.try_into() else {
return internal_error("http request decode error")
};

let res = match #func_name(request) {
Ok(res) => res,
Err(error) => {
return internal_error(error.to_string().as_str());
}
};

let Ok(response) = ::fastedge::http_handler::Response::try_from(res) else {
return internal_error("http response encode error")
};
response
}
}

).into()
}
2 changes: 2 additions & 0 deletions rust/examples/backend/.cargo/config.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[build]
target = "wasm32-wasi"
14 changes: 14 additions & 0 deletions rust/examples/backend/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
[package]
name = "backend"
version = "0.1.0"
edition = "2021"

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

[dependencies]
fastedge = {path="../../"}
anyhow = "1.0"
querystring = "1.1.0"

[workspace]
28 changes: 28 additions & 0 deletions rust/examples/backend/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
use anyhow::{anyhow, Error, Result};
use fastedge::body::Body;
use fastedge::http::{Method, Request, Response, StatusCode};

#[allow(dead_code)]
#[fastedge::http]
fn main(req: Request<Body>) -> Result<Response<Body>> {
let query = req
.uri()
.query()
.ok_or(anyhow!("missing uri query parameter"))?;
let params = querystring::querify(query);
let url = params
.iter()
.find(|(k, _)| k == &"url")
.ok_or(anyhow!("missing url parameter"))?;
let request = Request::builder()
.uri(url.1)
.method(Method::GET)
.body(Body::empty())?;

let response = fastedge::send_request(request).map_err(Error::msg)?;

Response::builder()
.status(StatusCode::OK)
.body(Body::from(format!("len = {}", response.body().len())))
.map_err(Error::msg)
}
2 changes: 2 additions & 0 deletions rust/examples/dummy/.cargo/config.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[build]
target = "wasm32-wasi"
13 changes: 13 additions & 0 deletions rust/examples/dummy/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
[package]
name = "dummy"
version = "0.1.0"
edition = "2021"

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

[dependencies]
fastedge = {path="../../"}
anyhow = "1.0"

[workspace]
12 changes: 12 additions & 0 deletions rust/examples/dummy/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
use anyhow::Result;
use fastedge::body::Body;
use fastedge::http::{Request, Response, StatusCode};

#[allow(dead_code)]
#[fastedge::http]
fn main(_req: Request<Body>) -> Result<Response<Body>> {
let res = Response::builder()
.status(StatusCode::OK)
.body(Body::empty())?;
Ok(res)
}
2 changes: 2 additions & 0 deletions rust/examples/print/.cargo/config.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[build]
target = "wasm32-wasi"
13 changes: 13 additions & 0 deletions rust/examples/print/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
[package]
name = "print"
version = "0.1.0"
edition = "2021"

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

[dependencies]
fastedge = {path="../../"}
anyhow = "1.0"

[workspace]
28 changes: 28 additions & 0 deletions rust/examples/print/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
use anyhow::Result;
use fastedge::body::Body;
use fastedge::http::{Request, Response, StatusCode};

#[allow(dead_code)]
#[fastedge::http]
fn main(req: Request<Body>) -> Result<Response<Body>> {
let mut body: String = "Method: ".to_string();
body.push_str(req.method().as_str());

body.push_str("\nURL: ");
body.push_str(req.uri().to_string().as_str());

body.push_str("\nHeaders:");
for (h, v) in req.headers() {
body.push_str("\n ");
body.push_str(h.as_str());
body.push_str(": ");
match v.to_str() {
Err(_) => body.push_str("not a valid text"),
Ok(a) => body.push_str(a),
}
}
let res = Response::builder()
.status(StatusCode::OK)
.body(Body::from(body))?;
Ok(res)
}
25 changes: 25 additions & 0 deletions rust/readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# The FastEdge Rust SDK

The Rust SDK is used to build FastEdge applications in Rust.

Example of usage:

```rust
// lib.rs
use anyhow::Result;
use fastedge::http::{Request, Response, StatusCode};
use fastedge::body::Body;

#[fastedge::http]
fn main(req: Request<Body>) -> Result<Response<Body>> {
Response::builder().status(StatusCode::OK).body(Body::empty())
}
```

The important things to note in the function above:

- the `fastedge::http` macro — this marks the function as the
entrypoint for the FastEdge application
- the function signature — `fn main(req: Request<Body>) -> Result<Response<Body>>` —
uses the HTTP objects from the popular Rust crate
[`http`](https://crates.io/crates/http)
53 changes: 53 additions & 0 deletions rust/src/backend.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
use crate::body::Body;
use crate::{witx_bindgen::http_backend, Error};

/// implementation of http_backend
pub fn send_request(req: ::http::Request<Body>) -> Result<::http::Response<Body>, Error> {
// convert http::Request<Body> to http_backend::Request
//let (parts, body) = req.into_parts();
let method = to_http_client_method(&req.method())?;
let headers = req
.headers()
.iter()
.map(|(name, value)| http_backend::Header {
key: name.as_str().as_bytes(),
value: value.to_str().unwrap().as_bytes(),
})
.collect::<Vec<http_backend::Header<'_>>>();
let uri = req.uri().to_string();
let request = http_backend::Request {
method,
uri: uri.as_bytes(),
headers: headers.as_slice(),
body: &req.body(),
};

println!("http_backend::send_request()");

// call http-backend component send_request
let response =
unsafe { http_backend::send_request(request) }.map_err(|e| Error::BackendError(e))?;

println!("http_backend::send_request() done");
let builder = http::Response::builder().status(response.status);
let builder = response
.headers
.iter()
.fold(builder, |builder, h| builder.header(h.key, h.value));

let body = Body::from(response.body);
let response = builder.body(body).map_err(|_| Error::InvalidBody)?;
Ok(response)
}

fn to_http_client_method(method: &::http::Method) -> Result<http_backend::Method, Error> {
Ok(match method {
&::http::Method::GET => http_backend::METHOD_GET,
&::http::Method::POST => http_backend::METHOD_POST,
&::http::Method::PUT => http_backend::METHOD_PUT,
&::http::Method::DELETE => http_backend::METHOD_DELETE,
&::http::Method::HEAD => http_backend::METHOD_HEAD,
&::http::Method::PATCH => http_backend::METHOD_PATCH,
method => return Err(Error::UnsupportedMethod(method.to_owned())),
})
}
Loading
Loading