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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
/**
 * 
 * This file represents the Rust "API" for Hive WASM runnables. The functions defined herein are used to exchange data
 * between the host (Hive, written in Go) and the Runnable (a WASM module, in this case written in Rust).
 * 
 */

 // a small wrapper to hold our dynamic Runnable
struct State <'a> {
    ident: i32,
    runnable: &'a dyn runnable::Runnable
}

// something to hold down the fort until a real Runnable is set
struct DefaultRunnable {}
impl runnable::Runnable for DefaultRunnable {
    fn run(&self, _input: Vec<u8>) -> Option<Vec<u8>> {
        return None;
    }
}

// the state that holds the user-provided Runnable and the current ident
static mut STATE: State = State {
    ident: 0,
    runnable: &DefaultRunnable{},
};

pub mod runnable {
    use std::mem;
    use std::slice;

    extern {
        fn return_result(result_pointer: *const u8, result_size: i32, ident: i32);
    }

    pub trait Runnable {
        fn run(&self, input: Vec<u8>) -> Option<Vec<u8>>;
    }

    pub fn set(runnable: &'static dyn Runnable) {
        unsafe {
            super::STATE.runnable = runnable;
        }
    }
    
    #[no_mangle]
    pub extern fn allocate(size: i32) -> *const u8 {
        let mut buffer = Vec::with_capacity(size as usize);
        let buffer_slice = buffer.as_mut_slice();
        let pointer = buffer_slice.as_mut_ptr();
        mem::forget(buffer_slice);
    
        pointer as *const u8
    }
    
    #[no_mangle]
    pub extern fn deallocate(pointer: *const u8, size: i32) {
        unsafe {
            let _ = slice::from_raw_parts(pointer, size as usize);
        }
    }
    
    #[no_mangle]
    pub extern fn run_e(pointer: *const u8, size: i32, ident: i32) {
        unsafe { super::STATE.ident = ident };
    
        // rebuild the memory into something usable
        let in_slice: &[u8] = unsafe { 
            slice::from_raw_parts(pointer, size as usize) 
        };
    
        let in_bytes = Vec::from(in_slice);
    
        // call the runnable and check its result
        let result: Vec<u8> = unsafe { match super::STATE.runnable.run(in_bytes) {
            Some(val) => val,
            None => Vec::from("run returned no data"), 
        } };
    
        let result_slice = result.as_slice();
        let result_size = result_slice.len();
    
    
        // call back to hive to return the result
        unsafe { 
            return_result(result_slice.as_ptr() as *const u8, result_size as i32, ident); 
        }
    }
}

pub mod http {
    use std::slice;

    static METHOD_GET: i32 = 1;

    extern {
        fn fetch_url(method: i32, url_pointer: *const u8, url_size: i32, body_pointer: *const u8, body_size: i32, dest_pointer: *const u8, dest_max_size: i32, ident: i32) -> i32;
    }

    pub fn get(url: &str) -> Vec<u8> {
        let mut dest_pointer: *const u8;
        let mut dest_size: i32;
        let mut capacity: i32 = 256000;

        // make the request, and if the response size is greater than that of capacity, double the capacity and try again
        loop {
            let cap = &mut capacity;

            let mut dest_bytes = Vec::with_capacity(*cap as usize);
            let dest_slice = dest_bytes.as_mut_slice();
            dest_pointer = dest_slice.as_mut_ptr() as *const u8;
    
            // do the request over FFI
            dest_size = unsafe { fetch_url(METHOD_GET, url.as_ptr(), url.len() as i32, 0 as *const u8, 0 as i32, dest_pointer, *cap, super::STATE.ident) };

            if dest_size < 0 {
                return Vec::from(format!("request_failed:{}", dest_size))
            } else if dest_size > *cap {
                super::log::info(format!("increasing capacity, need {}", dest_size).as_str());
                *cap = dest_size;
            } else {
                break;
            }
        }

        let result: &[u8] = unsafe {
            slice::from_raw_parts(dest_pointer, dest_size as usize)
        };

        return Vec::from(result)
    }
}

pub mod cache {
    use std::slice;

    extern {
        fn cache_set(key_pointer: *const u8, key_size: i32, value_pointer: *const u8, value_size: i32, ttl: i32, ident: i32) -> i32;
        fn cache_get(key_pointer: *const u8, key_size: i32, dest_pointer: *const u8, dest_max_size: i32, ident: i32) -> i32;
    }

    pub fn set(key: &str, val: Vec<u8>, ttl: i32) {
        let val_slice = val.as_slice();
        let val_ptr = val_slice.as_ptr();

        unsafe {
            cache_set(key.as_ptr(), key.len() as i32, val_ptr, val.len() as i32, ttl, super::STATE.ident);
        }
    }

    pub fn get(key: &str) -> Option<Vec<u8>> {
        let mut dest_pointer: *const u8;
        let mut result_size: i32;
        let mut capacity: i32 = 1024;

        // make the request, and if the response size is greater than that of capacity, double the capacity and try again
        loop {
            let cap = &mut capacity;

            let mut dest_bytes = Vec::with_capacity(*cap as usize);
            let dest_slice = dest_bytes.as_mut_slice();
            dest_pointer = dest_slice.as_mut_ptr() as *const u8;
    
            // do the request over FFI
            result_size = unsafe { cache_get(key.as_ptr(), key.len() as i32, dest_pointer, *cap, super::STATE.ident) };

            if result_size < 0 {
                return None;
            } else if result_size > *cap {
                super::log::info(format!("increasing capacity, need {}", result_size).as_str());
                *cap = result_size;
            } else {
                break;
            }
        }

        let result: &[u8] = unsafe {
            slice::from_raw_parts(dest_pointer, result_size as usize)
        };

        Some(Vec::from(result))
    }
}

pub mod req {
    use std::slice;
    use super::util;

    extern {
        fn request_get_field(field_type: i32, key_pointer: *const u8, key_size: i32, dest_pointer: *const u8, dest_max_size: i32, ident: i32) -> i32;
    }

    static FIELD_TYPE_META: i32 = 0 as i32;
    static FIELD_TYPE_BODY: i32 = 1 as i32;
    static FIELD_TYPE_HEADER: i32 = 2 as i32;
    static FIELD_TYPE_PARAMS: i32 = 3 as i32;
    static FIELD_TYPE_STATE: i32 = 4 as i32;

    pub fn method() -> String {
        match get_field(FIELD_TYPE_META, "method") {
            Some(bytes) => return util::to_string(bytes),
            None => return String::from("")
        }
    }
    
    pub fn url() -> String {
        match get_field(FIELD_TYPE_META, "url") {
            Some(bytes) => return util::to_string(bytes),
            None => return String::from("")
        }
    }
    
    pub fn id() -> String {
        match get_field(FIELD_TYPE_META, "id") {
            Some(bytes) => return util::to_string(bytes),
            None => return String::from("")
        }
    }
    
    pub fn body_raw() -> Vec<u8> {
        match get_field(FIELD_TYPE_META, "body") {
            Some(bytes) => return bytes,
            None => return util::to_vec(String::from(""))
        }
    }

    pub fn body_field(key: &str) -> String {
        match get_field(FIELD_TYPE_BODY, key) {
            Some(bytes) => return util::to_string(bytes),
            None => return String::from("")
        }
    }
    
    pub fn header(key: &str) -> String {
        match get_field(FIELD_TYPE_HEADER, key) {
            Some(bytes) => return util::to_string(bytes),
            None => return String::from("")
        }
    }
    
    pub fn url_param(key: &str) -> String {
        match get_field(FIELD_TYPE_PARAMS, key) {
            Some(bytes) => return util::to_string(bytes),
            None => return String::from("")
        }
    }
    
    pub fn state(key: &str) -> String {
        match get_field(FIELD_TYPE_STATE, key) {
            Some(bytes) => return util::to_string(bytes),
            None => return String::from("")
        }
    }
    
    fn get_field(field_type: i32, key: &str) -> Option<Vec<u8>> {
        let mut dest_pointer: *const u8;
        let mut result_size: i32;
        let mut capacity: i32 = 1024;

        // make the request, and if the response size is greater than that of capacity, double the capacity and try again
        loop {
            let cap = &mut capacity;

            let mut dest_bytes = Vec::with_capacity(*cap as usize);
            let dest_slice = dest_bytes.as_mut_slice();
            dest_pointer = dest_slice.as_mut_ptr() as *const u8;
    
            // do the request over FFI
            result_size = unsafe { request_get_field(field_type, key.as_ptr(), key.len() as i32, dest_pointer, *cap, super::STATE.ident) };

            if result_size < 0 {
                return None;
            } else if result_size > *cap {
                super::log::info(format!("increasing capacity, need {}", result_size).as_str());
                *cap = result_size;
            } else {
                break;
            }
        }

        let result: &[u8] = unsafe {
            slice::from_raw_parts(dest_pointer, result_size as usize)
        };

        Some(Vec::from(result))
    }
}

pub mod log {
    extern {
        fn log_msg(pointer: *const u8, result_size: i32, level: i32, ident: i32);
    }

    pub fn info(msg: &str) {
        log_at_level(msg, 3)
    }
    
    pub fn warn(msg: &str) {
        log_at_level(msg, 2)
    }
    
    pub fn error(msg: &str) {
        log_at_level(msg, 1)
    }

    fn log_at_level(msg: &str, level: i32) {
        let msg_vec = Vec::from(msg);
        let msg_slice = msg_vec.as_slice();
        let pointer = msg_slice.as_ptr();

        unsafe { log_msg(pointer, msg_slice.len() as i32, level, super::STATE.ident) };
    }
}

pub mod util {
    pub fn to_string(input: Vec<u8>) -> String {
        String::from_utf8(input).unwrap()
    }

    pub fn to_vec(input: String) -> Vec<u8> {
        input.as_bytes().to_vec()
    }

    pub fn str_to_vec(input: &str) -> Vec<u8> {
        String::from(input).as_bytes().to_vec()
    }
}