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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
/*
 * Copyright 2018, alex at staticlibs.net
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

//! Rust modules support for [Wilton JavaScript runtime](https://github.com/wiltonruntime/wilton)
//!
//! Usage example:
//!
//! ```
//!// configure Cargo to build a shared library
//!//[lib]
//!//crate-type = ["dylib"]
//!
//!// in lib.rs, import serde and wilton_rusty
//!//#[macro_use]
//!//extern crate serde_derive;
//!//extern crate wilton_rusty;
//!// ...
//!// declare input/output structs
//!#[derive(Deserialize)]
//!struct MyIn { }
//!#[derive(Serialize)]
//!struct MyOut { }
//!
//!// write a function that does some work
//!fn hello(obj: MyIn) -> MyOut { }
//!
//!// register that function inside the `wilton_module_init` function,
//!// that will be called by Wilton during the Rust module load
//!#[no_mangle]
//!pub extern "C" fn wilton_module_init() -> *mut std::os::raw::c_char {
//!    // register a call, error checking omitted
//!    wilton_rusty::register_wiltocall("hello", |obj: MyIn| { hello(obj) });
//!    // return success status to Wilton
//!    wilton_rusty::create_wilton_error(None)
//!}
//!
//! ```
//!
//! See an [example](https://github.com/wiltonruntime/wilton_examples/blob/master/rust/test.js#L17)
//! how to load and use Rust library from JavaScript.

extern crate serde;
extern crate serde_json;

use std::os::raw::*;
use std::ptr::null;
use std::ptr::null_mut;


// wilton C API import
// https://github.com/wiltonruntime/wilton_core/tree/master/include/wilton

extern "system" {

fn wilton_alloc(
    size_bytes: c_int
) -> *mut c_char;

fn wilton_free(
    buffer: *mut c_char
) -> ();

fn wiltoncall_register(
    call_name: *const c_char,
    call_name_len: c_int,
    call_ctx: *mut c_void,
    call_cb: extern "system" fn(
        call_ctx: *mut c_void,
        json_in: *const c_char,
        json_in_len: c_int,
        json_out: *mut *mut c_char,
        json_out_len: *mut c_int
    ) -> *mut c_char
) -> *mut c_char;

fn wiltoncall_runscript(
        script_engine_name: *const c_char,
        script_engine_name_len: c_int,
        json_in: *const c_char,
        json_in_len: c_int,
        json_out: *mut *mut c_char,
        json_out_len: *mut c_int
) -> *mut c_char;

}


static EMPTY_JSON_INPUT: &'static str = "{}";
type WiltonCallback = Box<dyn Fn(&[u8]) -> Result<String, String>>;


// helper functions

fn copy_to_wilton_bufer(data: &str) -> *mut c_char {
    unsafe {
        let res: *mut c_char = wilton_alloc((data.len() + 1) as c_int);
        std::ptr::copy_nonoverlapping(data.as_ptr() as *const c_char, res, data.len());
        *res.offset(data.len() as isize) = '\0' as c_char;
        res
    }
}

fn convert_wilton_error(err: *mut c_char) -> String {
    unsafe {
        use std::ffi::CStr;
        if null::<c_char>() != err {
            let res = match CStr::from_ptr(err).to_str() {
                Ok(val) => String::from(val),
                // generally cannot happen
                Err(_) => String::from("Unknown error")
            };
            wilton_free(err);
            res
        } else {
            // generally cannot happen
            String::from("No error")
        }
    }
}

// https://github.com/rustytools/errloc_macros/blob/79f5378e913293cb1b4a561fb7dc8d5cbcd09bc6/src/lib.rs#L44
fn panicmsg<'a>(e: &'a std::boxed::Box<dyn std::any::Any + std::marker::Send + 'static>) -> &'a str {
    match e.downcast_ref::<&str>() {
        Some(st) => st,
        None => {
            match e.downcast_ref::<std::string::String>() {
                Some(stw) => stw.as_str(),
                None => "()",
            }
        },
    }
}


// callback that is passed to wilton

#[no_mangle]
extern "system" fn wilton_cb(
    call_ctx: *mut c_void,
    json_in: *const c_char,
    json_in_len: c_int,
    json_out: *mut *mut c_char,
    json_out_len: *mut c_int
) -> *mut c_char {
    unsafe {
        std::panic::catch_unwind(|| {
            let data: &[u8] = if (null::<c_char>() != json_in) && (json_in_len > 0) {
                std::slice::from_raw_parts(json_in as *const u8, json_in_len as usize)
            } else {
                EMPTY_JSON_INPUT.as_bytes()
            };
            // https://stackoverflow.com/a/32270215/314015
            let callback_boxed_ptr = std::mem::transmute::<*mut c_void, *mut WiltonCallback>(call_ctx);
            let callback_boxed_ref: &mut WiltonCallback = &mut *callback_boxed_ptr;
            let callback_ref: &mut dyn Fn(&[u8]) -> Result<String, String> = &mut **callback_boxed_ref;
            match callback_ref(data) {
                Ok(res) => {
                    *json_out = copy_to_wilton_bufer(&res);
                    *json_out_len = res.len() as c_int;
                    null_mut::<c_char>()
                }
                Err(e) => copy_to_wilton_bufer(&e)
            }
        }).unwrap_or_else(|e| {
            copy_to_wilton_bufer(panicmsg(&e))
        })
    }
}

/// Registers a closure, that can be called from JavaScript
///
/// This function takes a closure and registers it with Wilton, so
/// it can be called from JavaScript using [wiltoncall](https://wiltonruntime.github.io/wilton/docs/html/namespacewiltoncall.html)
/// API.
///
/// Closure must take a single argument - a struct that implements [serde::Deserialize](https://docs.serde.rs/serde/trait.Deserialize.html)
/// and must return a struct that implements [serde::Serialize](https://docs.serde.rs/serde/trait.Serialize.html).
/// Closure input argument is converted from JavaScript object to Rust struct object.
/// Closure output is returned to JavaScript as a JSON (that can be immediately converted to JavaScript object).
///
/// If closure panics, its panic message is converted into JavaScript `Error` message (that can be
/// caugth and handled on JavaScript side).
///
///# Arguments
///
///* `name` - name this call, that should be used from JavaScript to invoke the closure
///* `callback` - closure, that will be called from JavaScript
///
///# Example
///
/// ```
/// // declare input/output structs
///#[derive(Deserialize)]
///struct MyIn { }
///#[derive(Serialize)]
///struct MyOut {  }
///
/// // write a function that does some work
///fn hello(obj: MyIn) -> MyOut { }
///
/// // register that function inside the `wilton_module_init` function,
/// // that will be called by Wilton during the Rust module load
///#[no_mangle]
///pub extern "C" fn wilton_module_init() -> *mut std::os::raw::c_char {
///    // register a call, error checking omitted
///    wilton_rusty::register_wiltocall("hello", |obj: MyIn| { hello(obj) });
///    // return success status to Wilton
///    wilton_rusty::create_wilton_error(None)
///}
///
/// ```
pub fn register_wiltocall<I: serde::de::DeserializeOwned, O: serde::Serialize, F: 'static + Fn(I) -> O>(
    name: &str,
    callback: F
) -> Result<(), String> {
    unsafe {
        let name_bytes = name.as_bytes();
        let callback_erased = move |json_in: &[u8]| -> Result<String, String> {
            match serde_json::from_slice(json_in) {
                Ok(obj_in) => {
                        let obj_out = callback(obj_in);
                        match serde_json::to_string_pretty(&obj_out) {
                            Ok(json_out) => Ok(json_out),
                            Err(e) => Err(String::from(e.to_string()))
                        }
                },
                Err(e) => Err(String::from(e.to_string()))
            }
        };
        let callback_fatty: WiltonCallback = Box::new(callback_erased);
        let callback_slim: Box<WiltonCallback> = Box::new(callback_fatty);
        let callback_bare: *mut WiltonCallback = Box::into_raw(callback_slim);
        // unboxed callbacks are leaked here: 16 byte per callback
        // it seems not easy to make their destructors to run after main
        // https://stackoverflow.com/a/27826181/314015
        // it may be easier to suppress wilton_module_init leaks in valgrind
        // let callback_unleak = Box::from_raw(callback_bare);

        let err: *mut c_char = wiltoncall_register(
            name_bytes.as_ptr() as *const c_char,
            name_bytes.len() as c_int,
            callback_bare as *mut c_void,
            wilton_cb);

        if null_mut::<c_char>() != err {
            Err(convert_wilton_error(err))
        } else {
            Ok(())
        }
    }
}

/// Create an error message, that can be passed back to Wilton
///
/// Helper function, that can be used with Rust `Result`s, returned
/// from `wilton_rusty::register_wiltoncall` function.
///
///# Arguments
///
///* `error_opt` - optional error message, that should be passed back to Wilton
///
///# Example
///
///```
/// // register a call
///let res = wilton_rusty::register_wiltocall("hello", |obj: MyObj1| { hello(obj) });
///
/// // check for error
///if res.is_err() {
///    // return error message to Wilton
///    // return wilton_rusty::create_wilton_error(res.err());
///    ()
///}
///
/// // return success status to Wilton
///wilton_rusty::create_wilton_error(None)
///()
///```
///
pub fn create_wilton_error(error_opt: Option<String>) -> *mut c_char {
    match error_opt {
        Some(msg) => copy_to_wilton_bufer(&msg),
        None => null_mut::<c_char>()
    }
}

/// Call JavaScript function
///
/// Allows to call a specified JavaScript function
/// passing arguments as a list of JSON values and receiving
/// result as a `String`.
///
///# Arguments (JSON call descriptor fields)
///
///* `module` -  name of the RequireJS module
///* `func` -  name of the function field in the module object (optional: not needed if module
/// itself is a function)
///* `args` -  function arguments (optional)
///
///# Example
///
///```
/// // create call descriptor
///let call_desc = json!({
///    "module": "lodash/string",
///    "func": "capitalize",
///    "args": [msg]
///});
///
/// // perform the call and check the results
///match wilton_rusty::runscript(&call_desc) {
///    Ok(res) => res,
///    Err(e) => panic!(e)
///}
///()
///```
///
pub fn runscript(call_desc: &serde_json::Value) -> Result<String, String> {
    unsafe {
        match serde_json::to_string_pretty(&call_desc) {
            Err(e) => Err(String::from(e.to_string())),
            Ok(ref mut json) => {
                let empty = String::new();
                json.push('\0'); // required by some of JS engines
                let json_bytes = json.as_bytes();
                let mut out: *mut c_char = null_mut::<c_char>();
                let mut out_len: c_int = 0;
                let err: *mut c_char = wiltoncall_runscript(
                    empty.as_bytes().as_ptr() as *const c_char,
                    0 as c_int,
                    json_bytes.as_ptr() as *const c_char,
                    (json_bytes.len() - 1) as c_int,
                    &mut out as *mut *mut c_char,
                    &mut out_len as *mut c_int);
                if null_mut::<c_char>() != err {
                    Err(convert_wilton_error(err))
                } else {
                    let res = if (null_mut::<c_char>() != out) && (out_len > 0) {
                        let slice = std::slice::from_raw_parts(out as *const u8, out_len as usize);
                        let vec = slice.to_vec();
                        match String::from_utf8(vec) {
                            Err(e) => Err(String::from(e.to_string())),
                            Ok(str) => Ok(str)
                        }
                    } else {
                        Ok(String::new())
                    };
                    if null_mut::<c_char>() != out {
                        wilton_free(out);
                    }
                    res
                }
            }
        }
    }
}