Skip to content

Commit

Permalink
Merge pull request #9 from blocklessnetwork/feature/refeact
Browse files Browse the repository at this point in the history
refeact
  • Loading branch information
Joinhack authored Jun 18, 2023
2 parents 513c89a + 964bb8c commit 2702f61
Show file tree
Hide file tree
Showing 8 changed files with 125 additions and 124 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "blockless-sdk"
version = "0.1.1"
version = "0.1.2"
authors = ["Join.G"]
description = "blockless runtime sdk"
keywords = ["blockless", "sdk"]
Expand Down
112 changes: 51 additions & 61 deletions src/cgi.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,8 @@
use std::fmt::{Display, Debug};
use std::fmt::{Debug, Display};

use json::{JsonValue, object::Object};
use json::{object::Object, JsonValue};

use crate::cgi_host::{
cgi_close,
cgi_list_exec,
cgi_list_read,
cgi_open,
cgi_stdout_read, cgi_stderr_read
};
use crate::{cgi_host::*, CGIErrorKind};

#[derive(Debug)]
pub struct CGIExtensions {
Expand All @@ -20,10 +14,10 @@ pub struct CGIExtensions {

impl Display for CGIExtensions {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let _ = f.write_fmt(format_args!("fileName: {}", self.file_name));
let _ = f.write_fmt(format_args!("alias: {}", self.alias));
let _ = f.write_fmt(format_args!("md5: {}", self.md5));
f.write_fmt(format_args!("description: {}", self.description))
write!(f, "fileName: {},", self.file_name)?;
write!(f, "alias: {},", self.alias)?;
write!(f, "md5: {},", self.md5)?;
write!(f, "description: {},", self.description)
}
}

Expand All @@ -36,13 +30,13 @@ pub struct CGICommand {
command: String,
args: Vec<String>,
envs: Vec<CGIEnv>,
handle: Option<u32>
handle: Option<u32>,
}

type ReadFn = unsafe extern "C" fn(u32, *mut u8, u32, *mut u32,) -> u32;
type ReadFn = unsafe extern "C" fn(u32, *mut u8, u32, *mut u32) -> u32;

impl CGICommand {
fn new(command: String, args: Vec<String>, envs: Vec<CGIEnv>) -> Self {
fn new(command: String, args: Vec<String>, envs: Vec<CGIEnv>) -> Self {
Self {
command,
args,
Expand All @@ -65,8 +59,8 @@ impl CGICommand {
}

fn read_all(&mut self, read_call: ReadFn) -> Result<Vec<u8>, CGIErrorKind> {
let mut readn = 0u32;
let mut data: Vec<u8> = Vec::new();
let mut readn = 0u32;
let mut data: Vec<u8> = Vec::new();
if self.handle.is_none() {
return Ok(data);
}
Expand Down Expand Up @@ -105,35 +99,31 @@ impl CGICommand {
let mut obj = Object::new();
let command = JsonValue::String(self.command.clone());
obj.insert("command", command);
let args = self.args.iter().map(|arg| {
JsonValue::String(arg.to_string())
}).collect::<Vec<_>>();
let args = self
.args
.iter()
.map(|arg| JsonValue::String(arg.to_string()))
.collect::<Vec<_>>();
obj.insert("args", JsonValue::Array(args));
let envs = self.envs.iter().map(|env| {
let mut obj = Object::new();
let name = JsonValue::String(env.name.clone());
obj.insert("name", name);
let value = JsonValue::String(env.value.clone());
obj.insert("value", value);
JsonValue::Object(obj)
}).collect::<Vec<_>>();
let envs = self
.envs
.iter()
.map(|env| {
let mut obj = Object::new();
let name = JsonValue::String(env.name.clone());
obj.insert("name", name);
let value = JsonValue::String(env.value.clone());
obj.insert("value", value);
JsonValue::Object(obj)
})
.collect::<Vec<_>>();
obj.insert("envs", JsonValue::Array(envs));
obj.dump()
}
}

#[derive(Debug)]
pub enum CGIErrorKind {
ListError,
EncodingError,
JsonDecodingError,
ExecError,
ReadError,
NoCGICommandError,
}

pub struct CGIListExtensions{
handle:u32,
pub struct CGIListExtensions {
handle: u32,
}

impl Drop for CGIListExtensions {
Expand All @@ -145,21 +135,21 @@ impl Drop for CGIListExtensions {
}

impl CGIListExtensions {
pub fn new() -> Result<Self, CGIErrorKind> {
pub fn new() -> Result<Self, CGIErrorKind> {
let mut cgi_handle: u32 = 0;
unsafe{
unsafe {
let rs = cgi_list_exec(&mut cgi_handle as *mut u32);
if rs != 0 {
return Err(CGIErrorKind::ListError);
}
};
Ok(CGIListExtensions{handle: cgi_handle})
Ok(CGIListExtensions { handle: cgi_handle })
}

fn list_read_all(&self) -> Result<Vec<u8>, CGIErrorKind> {
let mut data: Vec<u8> = Vec::new();
let mut bs = [0u8; 1024];
let mut readn = 0u32;
let mut readn = 0u32;
loop {
unsafe {
let rs = cgi_list_read(self.handle, &mut bs as _, bs.len() as _, &mut readn);
Expand All @@ -175,26 +165,26 @@ impl CGIListExtensions {
Ok(data)
}

pub fn command(&self, command: &str, args: Vec<String>, envs: Vec<CGIEnv>) -> Result<CGICommand, CGIErrorKind> {
pub fn command(
&self,
command: &str,
args: Vec<String>,
envs: Vec<CGIEnv>,
) -> Result<CGICommand, CGIErrorKind> {
let extensions = self.list()?;
extensions.iter()
.find(|ext| {
if &ext.alias == command {
true
} else {
false
}
}).map(|_| CGICommand::new(command.to_string(), args, envs))
.ok_or(CGIErrorKind::NoCGICommandError)
extensions
.iter()
.find(|ext| if &ext.alias == command { true } else { false })
.map(|_| CGICommand::new(command.to_string(), args, envs))
.ok_or(CGIErrorKind::NoCommandError)
}

pub fn list(&self) -> Result<Vec<CGIExtensions>, CGIErrorKind> {
let data = self.list_read_all()?;
let s = std::str::from_utf8(&data)
.map_err(|_| CGIErrorKind::EncodingError)?;
let json = json::parse(s)
.map_err(|_| CGIErrorKind::JsonDecodingError)?;
let externs = json.members()
let s = std::str::from_utf8(&data).map_err(|_| CGIErrorKind::EncodingError)?;
let json = json::parse(s).map_err(|_| CGIErrorKind::JsonDecodingError)?;
let externs = json
.members()
.map(|json| {
let file_name = json["fileName"].as_str().unwrap_or("").to_string();
let alias = json["alias"].as_str().unwrap_or("").to_string();
Expand All @@ -210,4 +200,4 @@ impl CGIListExtensions {
.collect::<Vec<_>>();
Ok(externs)
}
}
}
45 changes: 9 additions & 36 deletions src/cgi_host.rs
Original file line number Diff line number Diff line change
@@ -1,52 +1,25 @@
#[link(wasm_import_module = "blockless_cgi")]
extern "C" {
#[link_name = "cgi_open"]
pub(crate) fn cgi_open(
opts: *const u8,
opts_len: u32,
cgi_handle: *mut u32,
) -> u32;
pub(crate) fn cgi_open(opts: *const u8, opts_len: u32, cgi_handle: *mut u32) -> u32;

#[link_name = "cgi_stdout_read"]
pub(crate) fn cgi_stdout_read(
handle: u32,
buf: *mut u8,
buf_len: u32,
num: *mut u32,
) -> u32;
pub(crate) fn cgi_stdout_read(handle: u32, buf: *mut u8, buf_len: u32, num: *mut u32) -> u32;

#[link_name = "cgi_stderr_read"]
pub(crate) fn cgi_stderr_read(
handle: u32,
buf: *mut u8,
buf_len: u32,
num: *mut u32,
) -> u32;
pub(crate) fn cgi_stderr_read(handle: u32, buf: *mut u8, buf_len: u32, num: *mut u32) -> u32;

#[link_name = "cgi_stdin_write"]
pub(crate) fn cgi_stdin_write(
handle: u32,
buf: *const u8,
buf_len: u32,
num: *mut u32,
) -> u32;
#[allow(dead_code)]
pub(crate) fn cgi_stdin_write(handle: u32, buf: *const u8, buf_len: u32, num: *mut u32) -> u32;

#[link_name = "cgi_close"]
pub(crate) fn cgi_close(
handle: u32,
) -> u32;
pub(crate) fn cgi_close(handle: u32) -> u32;

#[link_name = "cgi_list_exec"]
pub(crate) fn cgi_list_exec(
cgi_handle: *mut u32,
) -> u32;
pub(crate) fn cgi_list_exec(cgi_handle: *mut u32) -> u32;

#[link_name = "cgi_list_read"]
pub(crate) fn cgi_list_read(
handle: u32,
buf: *mut u8,
buf_len: u32,
num: *mut u32,
) -> u32;

pub(crate) fn cgi_list_read(handle: u32, buf: *mut u8, buf_len: u32, num: *mut u32) -> u32;

}
46 changes: 46 additions & 0 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,3 +59,49 @@ impl From<u32> for HttpErrorKind {
}
}
}

#[derive(Debug)]
pub enum SocketErrorKind {
ConnectRefused,
ParameterError,
ConnectionReset,
AddressInUse,
}

impl std::fmt::Display for SocketErrorKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match *self {
SocketErrorKind::ConnectRefused => write!(f, "Connect Refused."),
SocketErrorKind::ParameterError => write!(f, "Parameter Error."),
SocketErrorKind::ConnectionReset => write!(f, "Connection Reset."),
SocketErrorKind::AddressInUse => write!(f, "Address In Use."),
}
}
}

impl std::error::Error for SocketErrorKind {}

#[derive(Debug)]
pub enum CGIErrorKind {
ListError,
EncodingError,
JsonDecodingError,
ExecError,
ReadError,
NoCommandError,
}

impl std::fmt::Display for CGIErrorKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match *self {
CGIErrorKind::ListError => write!(f, "CGI List Error."),
CGIErrorKind::EncodingError => write!(f, "CGI Encoding Error."),
CGIErrorKind::JsonDecodingError => write!(f, "Json decoding Error."),
CGIErrorKind::ExecError => write!(f, "CGI Exec Error."),
CGIErrorKind::ReadError => write!(f, "Read Error."),
CGIErrorKind::NoCommandError => write!(f, "No CGI Command Error."),
}
}
}

impl std::error::Error for CGIErrorKind {}
13 changes: 3 additions & 10 deletions src/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,14 +73,8 @@ impl BlocklessHttp {
loop {
let mut buf = [0u8; 1024];
let mut num: u32 = 0;
let rs = unsafe {
http_read_body(
self.inner,
buf.as_mut_ptr(),
buf.len() as _,
&mut num,
)
};
let rs =
unsafe { http_read_body(self.inner, buf.as_mut_ptr(), buf.len() as _, &mut num) };
if rs != 0 {
return Err(HttpErrorKind::from(rs));
}
Expand Down Expand Up @@ -127,8 +121,7 @@ impl BlocklessHttp {

pub fn read_body(&self, buf: &mut [u8]) -> Result<u32, HttpErrorKind> {
let mut num: u32 = 0;
let rs =
unsafe { http_read_body(self.inner, buf.as_mut_ptr(), buf.len() as _, &mut num) };
let rs = unsafe { http_read_body(self.inner, buf.as_mut_ptr(), buf.len() as _, &mut num) };
if rs != 0 {
return Err(HttpErrorKind::from(rs));
}
Expand Down
10 changes: 5 additions & 5 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
mod cgi;
mod cgi_host;
mod error;
mod http;
mod http_host;
mod cgi_host;
mod cgi;
mod socket_host;
mod socket;
mod socket_host;

pub use socket::*;
pub use cgi::*;
pub use http::*;
pub use error::*;
pub use http::*;
pub use socket::*;
15 changes: 5 additions & 10 deletions src/socket.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,7 @@
use crate::socket_host::create_tcp_bind_socket_native;

#[derive(Debug)]
pub enum SocketErrorKind {
ConnectRefused,
ParameterError,
ConnectionReset,
AddressInUse,
}
use crate::{
socket_host::*,
SocketErrorKind
};

pub fn create_tcp_bind_socket(addr: &str) -> Result<u32, SocketErrorKind> {
unsafe {
Expand All @@ -24,4 +19,4 @@ pub fn create_tcp_bind_socket(addr: &str) -> Result<u32, SocketErrorKind> {
_ => unreachable!("unreach."),
})
}
}
}
6 changes: 5 additions & 1 deletion src/socket_host.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
#[link(wasm_import_module = "blockless_socket")]
extern "C" {
#[link_name = "create_tcp_bind_socket"]
pub(crate) fn create_tcp_bind_socket_native(addr: *const u8, addr_len: u32, fd: *mut u32) -> u32;
pub(crate) fn create_tcp_bind_socket_native(
addr: *const u8,
addr_len: u32,
fd: *mut u32,
) -> u32;
}

0 comments on commit 2702f61

Please sign in to comment.