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
// Copyright 2015-2019 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 operation of the delivered message and handle it accordingly,
//! returning any binary payload in response. It is the responsibility of the guest module to ensure
//! that the capability provider will be able to understand whichever messages it sends.
//!
//! # Example
//! ```
//! extern crate wascap_guest as guest;
//!
//! use guest::prelude::*;
//!
//! call_handler!(handle_call);
//!
//! pub fn handle_call(ctx: &CapabilitiesContext, operation: &str, msg: &[u8]) -> CallResult {
//!     match operation {
//!         http::OP_HANDLE_REQUEST => hello_world(ctx, msg),
//!         core::OP_HEALTH_REQUEST => Ok(vec![]),
//!         _ => Err("bad dispatch".into()),
//!     }     
//! }
//!
//! fn hello_world(
//!    _ctx: &CapabilitiesContext,
//!    _msg: &[u8]) -> CallResult {
//!     Ok(vec![])
//! }
//! ```

pub extern crate prost;
pub extern crate wascap_codec;
use crate::kv::KeyValueStore;
use crate::msg::MessageBroker;
use crate::raw::RawCapability;
use std::rc::Rc;

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

#[link(wasm_import_module = "wapc")]
extern "C" {
    pub fn __console_log(ptr: *const u8, len: usize);
    pub fn __host_call(op_ptr: *const u8, op_len: usize, ptr: *const u8, len: usize) -> usize;
    pub fn __host_response(ptr: *const u8);
    pub fn __host_response_len() -> usize;
    pub fn __host_error_len() -> usize;
    pub fn __host_error(ptr: *const u8);
    pub fn __guest_response(ptr: *const u8, len: usize);
    pub fn __guest_error(ptr: *const u8, len: usize);    
    pub fn __guest_request(op_ptr: *const u8, ptr: *const u8);
}

/// 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, op: &str, msg: &[u8]) -> Result<Vec<u8>>;
}

/// 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, Default)]
pub struct WascapHostRuntimeInterface {}

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

impl HostRuntimeInterface for WascapHostRuntimeInterface {

    /// The function through which all host calls take place. 
    fn do_host_call(&self, op: &str, msg: &[u8]) -> Result<Vec<u8>> {
     
        let callresult = unsafe {
            __host_call(op.as_ptr(), op.len() as _, msg.as_ptr(), msg.len() as _)            
        };
        if callresult != 1 { // call was not successful
            let errlen = unsafe { __host_error_len() };
            let buf = Vec::with_capacity(errlen as _);
            let retptr = buf.as_ptr();
            let slice = unsafe {
                __host_error(retptr);
                std::slice::from_raw_parts(retptr as _, errlen as _)
            };
            Err(errors::new(errors::ErrorKind::HostError(
                String::from_utf8(slice.to_vec()).unwrap(),
            )))
        } else { // call succeeded
            let len = unsafe { __host_response_len() };
            let buf = Vec::with_capacity(len as _);
            let retptr = buf.as_ptr();
            let slice = unsafe {
                __host_response(retptr);
                std::slice::from_raw_parts(retptr as _, len as _)
            };
            Ok(slice.to_vec())
        }
    }
}

/// Utility function to easily convert a prost Message into a byte vector
pub fn protobytes(msg: impl prost::Message) -> Result<Vec<u8>> {
    let mut buf = Vec::new();
    msg.encode(&mut buf)?;
    Ok(buf)
}

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

            let buf: Vec<u8> = Vec::with_capacity(req_len as _);
            let req_ptr = buf.as_ptr();

            let opbuf: Vec<u8> = Vec::with_capacity(op_len as _);
            let op_ptr = opbuf.as_ptr();

            let (slice, op) = unsafe {
                $crate::__guest_request(op_ptr, req_ptr);
                (
                    slice::from_raw_parts(req_ptr, req_len as _),
                    slice::from_raw_parts(op_ptr, op_len as _),
                )
            };

            let opstr = ::std::str::from_utf8(op).unwrap();
            let ctx = $crate::CapabilitiesContext::from_hri(Rc::new(&$crate::HRI));

            ctx.log(&format!(
                "Performing guest call, operation - {}",
                opstr                
            ));
            match $user_handler(&ctx, &opstr, slice) {
                Ok(msg) => unsafe {
                    $crate::__guest_response(msg.as_ptr(), msg.len() as _);
                    1
                },
                Err(e) => {
                    let errmsg = format!("Guest call failed: {}", e);
                    ctx.log(&errmsg);
                    unsafe {
                        $crate::__guest_error(errmsg.as_ptr(), errmsg.len() as _);
                    }
                    0
                }
            }
        }
    };
}

#[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 kv;
pub mod msg;
pub mod prelude;
pub mod raw;