flawless_wasabi/
lib.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
//! A WebAssembly ABI for flawless, inspired by io_uring.
//!
//! Based on the idea that all calls between the guest and host space are done through one function called
//! `submit`. This function will take a buffer as input and return a buffer as output. The input buffer
//! contains commands serialized as JSON. Similarly, the output buffer will contain results of the commands
//! serialized with JSON.
//!
//! This crate contains the definitions of the types that are serialized and deserialized. It is shared
//! between the guest and host.

use std::time::{Duration, SystemTime};

use serde::{Deserialize, Serialize};

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Input {
    GetInput,
    Log(Level),
    SendResponse(String),
    Random(Types),
    Sleep(std::time::Duration),
    HTTPRequest(HttpRequest),
    GetSecret(String),
    TimeNow,
    RecvMessage(Option<Duration>, Vec<String>),
    StartWorkflow(String, String),
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Output {
    Unit,
    Value(Types),
    String(String),
    ResponseSent(bool),
    HTTPResponse(Result<HttpResponse, HttpError>),
    Time(SystemTime),
    Message(String, String),
    Timeout,
    Secret(Option<String>),
}

#[derive(Copy, Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Types {
    Bool(bool),
    I32(i32),
    I64(i64),
    F32(f32),
    F64(f64),
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Level {
    Info(String),
    Warn(String),
    Error(String),
    Debug(String),
    Trace(String),
}

#[derive(Copy, Clone, Debug, PartialEq)]
pub enum Error {
    NoAllocExport = -1,
    NoMemoryExport = -2,
    AllocCallFailed = -3,
    InputSerializationFailed = -4,
    InputDeserializationFailed = -5,
    OutputSerializationFailed = -6,
    OutputWriteFailed = -7,
    OutputDeserializationFailed = -8,
}

impl Error {
    /// Creates new error from the `i32` representation.
    pub fn from_code(value: i32) -> Self {
        match value {
            -1 => Error::NoAllocExport,
            -2 => Error::NoMemoryExport,
            -3 => Error::AllocCallFailed,
            -4 => Error::InputSerializationFailed,
            -5 => Error::InputDeserializationFailed,
            -6 => Error::OutputSerializationFailed,
            -7 => Error::OutputWriteFailed,
            -8 => Error::OutputDeserializationFailed,
            _ => unreachable!("unknown error code"),
        }
    }

    /// Returns the `i32` representation of the error.
    pub fn code(&self) -> i32 {
        *self as i32
    }
}

#[derive(Copy, Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct HttpConfig {
    pub idempotent: bool,
    pub timeout: std::time::Duration,
    pub response_body_limit: u64,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct HttpRequest {
    pub config: HttpConfig,
    pub method: String,
    pub url: String,
    pub headers: Vec<(String, String)>,
    pub body: Vec<u8>,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct HttpResponse {
    pub status_code: u16,
    pub url: String,
    pub headers: Vec<(String, String)>,
    pub body: Vec<u8>,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum HttpError {
    Status(u16, HttpResponse),
    Transport(HttpTransportError),
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct HttpTransportError {
    pub kind: HttpErrorKind,
    pub message: Option<String>,
    pub url: Option<String>,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum HttpErrorKind {
    InvalidUrl,
    UnknownScheme,
    Dns,
    ConnectionFailed,
    TooManyRedirects,
    BadStatus,
    BadHeader,
    RequestInterrupted,
    Io,
    StatusCode,
}

#[export_name = "wasabi::alloc"]
pub fn alloc(capacity: usize) -> *const u8 {
    let allocation = Vec::with_capacity(capacity);
    let ptr = allocation.as_ptr();
    std::mem::forget(allocation);
    ptr
}

#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
mod abi {
    #[link(wasm_import_module = "wasabi")]
    extern "C" {
        pub fn submit(in_ptr: *const u8, in_len: usize, out_ptr: *mut *mut u8, out_len: *mut usize) -> i32;
    }
}

#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
pub fn submit(input: &Input) -> Result<Output, Error> {
    let input = match serde_json::to_string(input) {
        Ok(input) => input,
        Err(_) => return Err(Error::InputSerializationFailed),
    };
    let mut out_ptr: *mut u8 = std::ptr::null_mut();
    let mut out_len: usize = 0;
    let output = unsafe {
        match abi::submit(input.as_ptr(), input.len(), &mut out_ptr as *mut *mut u8, &mut out_len) {
            0 => (), // success
            error_code => return Err(Error::from_code(error_code)),
        };
        Vec::from_raw_parts(out_ptr, out_len, out_len)
    };

    match serde_json::from_slice(&output) {
        Ok(output) => Ok(output),
        Err(_) => Err(Error::OutputDeserializationFailed),
    }
}

#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
pub fn submit(_input: &Input) -> Result<Output, Error> {
    unreachable!("`submit` can only be used inside the flawless runtime")
}