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
// Copyright 2015-2018 Capital One Services, LLC
//
// 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.

//! # wascap-guest
//! 
//! The `wascap-guest` library provides WebAssembly module developers with access to a 
//! [wascap](https://wascap.io)-compliant host runtime. Each guest module has a single
//! call handler, declared with the `call_handler!` macro. Inside this call handler, the guest
//! module should check the _type URI_ of the delivered command and handle the command accordingly,
//! returning an `Event` in response.
//! 
//! # Example
//! ```
//! extern crate wascap_guest as guest;
//! 
//! use guest::prelude::*;
//! 
//! call_handler!(handle_call);
//! 
//! pub fn handle_call(ctx: &CapabilitiesContext, cmd: &Command) -> Result<Event> {
//!     match cmd.payload {
//!         Some(ref p) => match p.type_url.as_ref() {
//!             http::TYPE_URL_HTTP_REQUEST => hello_world(ctx, p.value.as_slice()),
//!             core::TYPE_URL_HEALTH_REQUEST => Ok(Event::success()),
//!             _ => Ok(Event::bad_dispatch(&p.type_url)),
//!         },
//!         None => Ok(http::Response::bad_request().as_event(true, None)),
//!     }
//! }
//! 
//! fn hello_world(
//!    ctx: &CapabilitiesContext,
//!    payload: impl Into<http::Request>) -> Result<Event> {
//!     Ok(http::Response::ok().as_event(true, None))
//! }
//! ```

pub extern crate prost;
pub extern crate wascap_codec;

use std::rc::Rc;
use crate::kv::KeyValueStore;
use crate::msg::MessageBroker;
use crate::raw::RawCapability;
use prost::Message;
use wascap_codec as codec;

/// Wascap Guest SDK result type
pub type Result<T> = std::result::Result<T, errors::Error>;

/// Source ID for guest modules
pub const SOURCE_GUEST: &'static str = "guest";

#[link(wasm_import_module = "wascap")]
extern "C" {
    fn __throw(a: *const u8, b: usize) -> !;
    fn __console_log(ptr: *const u8, len: usize);
    fn __host_call(ptr: *const u8, len: usize, retptr: *const u8) -> i32;
}

/// A trait for a host runtime interface. This abstracts the method of invoking 
/// host calls so that the host interface can be mocked for testing
pub trait HostRuntimeInterface {
    fn do_host_call(&self, cmd: &codec::core::Command) -> Result<codec::core::Event>;
}

/// The singleton Host Runtime Interface for doing real, unsafe FFI calls to the runtime host
pub const HRI: WascapHostRuntimeInterface = WascapHostRuntimeInterface{};

/// The default implementation of the host runtime interface. This is the runtime interface
/// that will be inside the Capabilities Context passed to a guest module's call handler
#[derive(Clone)]
pub struct WascapHostRuntimeInterface {}

impl WascapHostRuntimeInterface {
    pub fn new() -> WascapHostRuntimeInterface {
        WascapHostRuntimeInterface {}
    }
}

impl HostRuntimeInterface for WascapHostRuntimeInterface {
    fn do_host_call(&self, cmd: &codec::core::Command) -> Result<codec::core::Event> {
        let mut cmdbytes = Vec::new();
        cmd.encode(&mut cmdbytes)?;

        let result_slice = unsafe {
            let mut __stack = { guestmem::GlobalStack::new() };
            let buf: Vec<u8> = Vec::new();
            let retptr = buf.as_ptr();
            //__stack.push(buf.as_ptr() as u32);
            let result_len = { __host_call(cmdbytes.as_ptr(), cmdbytes.len() as _, retptr) };
            std::slice::from_raw_parts(retptr as _, result_len as _)
        };

        let event = codec::core::Event::decode(result_slice)?;
        Ok(event)
    }
}


#[macro_export]
macro_rules! call_handler {
    ($user_handler:ident) => {
        #[no_mangle]
        pub extern "C" fn __guest_call(param_ptr: i32, len: i32) -> i32 {
            use std::slice;
            use std::rc::Rc;
            use $crate::guestmem;
            use $crate::guestmem::Stack;
            use $crate::prost::Message;

            let req = {
                let mut __stack = unsafe { guestmem::GlobalStack::new() };
                let slice = unsafe { slice::from_raw_parts(param_ptr as _, len as _) };
                let cmd = $crate::wascap_codec::core::Command::decode(&slice).unwrap();
                //let req = Request::from(raw_req);

                let ctx = $crate::CapabilitiesContext::from_hri(Rc::new(&$crate::HRI));

                ctx.log("Invoking handler...");
                let event: $crate::wascap_codec::core::Event = match $user_handler(&ctx, &cmd) {
                    Ok(evt) => evt,
                    Err(e) => {
                        ctx.log(&format!("Handler failed: {}", e));
                        $crate::wascap_codec::core::Event {
                            success: false,
                            error: Some($crate::wascap_codec::core::Error {
                                code: 500,
                                description: format!("{}", e),
                            }),
                            payload: None,
                        }
                    }
                };

                let mut buf = Vec::with_capacity(event.encoded_len());
                let _res = event.encode(&mut buf).unwrap();
                __stack.push(buf.as_ptr() as u32);
                //__stack.push(buf.len() as u32);

                buf.len() as _
            };
            req
        }
    };
}

#[cold]
#[inline(never)]
pub(crate) fn throw_str(s: &str) -> ! {
    unsafe {
        __throw(s.as_ptr(), s.len());
    }
}

#[cold]
#[inline(never)]
pub(crate) fn console_log(s: &str) {
    unsafe {
        __console_log(s.as_ptr(), s.len());
    }
}

/// The capabilities context is the gateway through which all guest modules communicate with a host runtime. A reference
/// to a capabilities context is passed to the call handler defined by the guest module. Individual capabilities are separated
/// through function calls for each capability provider, including any bound opaque `raw` providers.
pub struct CapabilitiesContext {    
    kv: KeyValueStore,    
    msg: MessageBroker,
    raw: RawCapability,
}

impl CapabilitiesContext {
    
    pub fn from_hri(hri: Rc<&'static dyn HostRuntimeInterface>) -> CapabilitiesContext {            
        CapabilitiesContext {            
            kv: KeyValueStore::new(hri.clone()),
            msg: MessageBroker::new(hri.clone()),
            raw: RawCapability::new(hri),
        }

    }

    pub fn kv(&self) -> &KeyValueStore {
        &self.kv
    }

    pub fn msg(&self) -> &MessageBroker {
        &self.msg
    }

    pub fn raw(&self) -> &RawCapability {
        &self.raw
    }

    pub fn log(&self, msg: &str) {
        console_log(msg);
    }
}

mod errors;
pub mod guestmem;
pub mod kv;
pub mod prelude;
pub mod raw;
pub mod msg;