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
//! 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 with bincode. Similarly, the output buffer will contain results of the
//! commands serialized with bincode.
//!
//! This crate contains the definitions of the types that are serialized and deserialized. It is shared
//! between the guest and host.

#[cfg(feature = "ureq")]
mod ureq;

use std::time::SystemTime;

use serde::{Deserialize, Serialize};

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Input {
    GetInput,
    SetData(String),
    Random(Types),
    Log(Level),
    Sleep(std::time::Duration),
    HTTPRequest(HttpRequest),
    GetSecret(String),
    TimeNow,
    LockState(String),
    UnlockState(String),
    GetState(String),
    SetState((String, String)),
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Output {
    Unit,
    Value(Types),
    String(String),
    HTTPResponse(Result<HttpResponse, HttpError>),
    GetSecret(Option<String>),
    Time(SystemTime),
    State(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,
    InputDeserializationFailed = -4,
    OutputSerializationFailed = -5,
    OutputWriteFailed = -6,
}

impl Error {
    /// Creates new error from the `i32` representation.
    pub fn from_code(value: i32) -> Self {
        match value {
            -1 => Error::NoMemoryExport,
            _ => 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,
    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, bincode::Error> {
    let input = bincode::serialize(input)?;
    let mut out_ptr: *mut u8 = std::ptr::null_mut();
    let mut out_len: usize = 0;
    let output = unsafe {
        abi::submit(input.as_ptr(), input.len(), &mut out_ptr as *mut *mut u8, &mut out_len);
        Vec::from_raw_parts(out_ptr, out_len, out_len)
    };
    bincode::deserialize(&output)
}

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