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
// 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-codec
//! 
//! This library provides the core set of types and associated functions used to facilitate guest module
//! and host runtime communication for Waxosuit. 

use prost_types;

#[macro_use]
extern crate serde_derive;

macro_rules! command {
    ($msgid:ident, $typ:ty) => {
        impl crate::AsCommand for $typ {
            fn as_command(&self, source: &str, target_cap: &str) -> crate::core::Command {
                crate::create_command(self, $msgid, source, target_cap)
            }
        }
    };
}

macro_rules! event {
    ($msgid:ident, $typ:ty) => {
        impl crate::AsEvent for $typ {
            fn as_event(&self, success: bool, error: Option<(i32, &str)>) -> crate::core::Event {
                crate::create_event(Some(self), $msgid, success, error)
            }
        }
    };
}

pub mod http {
    //! # HTTP server capability data structures
    //! 
    //! This module contains data types for the `wascap:http_server` capability.
    include!(concat!(env!("OUT_DIR"), "/http.rs"));

    use prost::Message;
    use serde::ser::Serialize;
    use std::collections::HashMap;

    pub const TYPE_URL_HTTP_REQUEST: &'static str = "type.wascap.io/http.Request";
    pub const TYPE_URL_HTTP_RESPONSE: &'static str = "type.wascap.io/http.Response";

    command!(TYPE_URL_HTTP_REQUEST, Request);
    event!(TYPE_URL_HTTP_RESPONSE, Response);

    impl Into<Request> for &[u8] {
        fn into(self) -> Request {
            Request::decode(self).unwrap()
        }
    }

    impl Into<Response> for &[u8] {
        fn into(self) -> Response {
            Response::decode(self).unwrap()
        }
    }

    impl Response {
        /// Creates a response with a given status code and serializes the given payload as JSON
        pub fn json<T>(payload: T, status_code: u32, status: &str) -> Response
        where
            T: Serialize,
        {
            Response {
                body: serde_json::to_string(&payload).unwrap().into_bytes(),
                header: HashMap::new(),
                status: status.to_string(),
                status_code: status_code,
            }
        }

        /// Handy shortcut for creating a 404/Not Found response
        pub fn not_found() -> Response {
            Response {
                status: "Not Found".to_string(),
                status_code: 404,
                ..Default::default()
            }
        }

        /// Useful shortcut for creating a 200/OK response
        pub fn ok() -> Response {
            Response {
                status: "OK".to_string(),
                status_code: 200,
                ..Default::default()
            }
        }

        /// Useful shortcut for creating a 500/Internal Server Error response
        pub fn internal_server_error(msg: &str) -> Response {
            Response {
                status: "Internal Server Error".to_string(),
                status_code: 500,
                body: msg.to_string().as_bytes().into(),
                ..Default::default()
            }
        }

        /// Shortcut for creating a 400/Bad Request response
        pub fn bad_request() -> Response {
            Response {
                status: "Bad Request".to_string(),
                status_code: 400,
                ..Default::default()
            }
        }
    }
}

pub mod core {
//! # Core data types
//! 
//! This module contains data types used for Wascap guest module and host runtime communications
    include!(concat!(env!("OUT_DIR"), "/core.rs"));

    pub const TYPE_URL_LIVE_UPDATE: &'static str = "type.wascap.io/core.LiveUpdate";
    pub const TYPE_URL_HEALTH_REQUEST: &'static str = "type.wascap.io/core.HealthRequest";

    command!(TYPE_URL_LIVE_UPDATE, LiveUpdate);
    command!(TYPE_URL_HEALTH_REQUEST, HealthRequest);

    impl Event {
        pub fn bad_dispatch(type_url: &str) -> Event {
            Event {
                success: false,
                payload: None,
                error: Some(Error {
                    code: -100,
                    description: format!("Guest module rejected command: {}", type_url),
                }),
            }
        }

        pub fn success() -> Event {
            Event {
                success: true,
                payload: None,
                error: None,
            }
        }
    }
}

pub mod messaging {
//! # Message Broker Data Types
//! 
//! This module contains data types for the `wascap:messaging` capability provider
    use prost::Message;

    include!(concat!(env!("OUT_DIR"), "/messaging.rs"));

    pub const TYPE_URL_DELIVER_MESSAGE: &'static str = "type.wascap.io/messaging.DeliverMessage";
    pub const TYPE_URL_PUBLISH_MESSAGE: &'static str = "type.wascap.io/messaging.PublishMessage";

    impl Into<DeliverMessage> for &Vec<u8> {
        fn into(self) -> DeliverMessage {
            DeliverMessage::decode(self.as_slice()).unwrap()
        }
    }

    impl Into<PublishMessage> for &Vec<u8> {
        fn into(self) -> PublishMessage {
            PublishMessage::decode(self.as_slice()).unwrap()
        }
    }

    command!(TYPE_URL_DELIVER_MESSAGE, DeliverMessage);
    command!(TYPE_URL_PUBLISH_MESSAGE, PublishMessage);
}

pub mod keyvalue {
//! # Key-Value Store Data Types
//! 
//! This module contains data types for the `wascap:keyvalue` capability provider
    include!(concat!(env!("OUT_DIR"), "/keyvalue.rs"));

    pub const TYPE_URL_GET_REQUEST: &'static str = "type.wascap.io/keyvalue.GetRequest";
    pub const TYPE_URL_GET_RESPONSE: &'static str = "type.wascap.io/keyvalue.GetResponse";
    pub const TYPE_URL_SET_REQUEST: &'static str = "type.wascap.io/keyvalue.SetRequest";
    pub const TYPE_URL_ADD_REQUEST: &'static str = "type.wascap.io/keyvalue.AddRequest";
    pub const TYPE_URL_ADD_RESPONSE: &'static str = "type.wascap.io/keyvalue.AddResponse";
    pub const TYPE_URL_LIST_PUSH_REQUEST: &'static str = "type.wascap.io/keyvalue.ListPushRequest";
    pub const TYPE_URL_LIST_RESPONSE: &'static str = "type.wascap.io/keyvalue.ListResponse";
    pub const TYPE_URL_LIST_CLEAR_REQUEST: &'static str =
        "type.wascap.io/keyvalue.ListClearRequest";
    pub const TYPE_URL_LIST_RANGE_REQUEST: &'static str =
        "type.wascap.io/keyvalue.ListRangeRequest";
    pub const TYPE_URL_LIST_RANGE_RESPONSE: &'static str =
        "type.wascap.io/keyvalue.ListRangeResponse";
    pub const TYPE_URL_DEL_REQUEST: &'static str = "type.wascap.io/keyvalue.DelRequest";

    command!(TYPE_URL_GET_REQUEST, GetRequest);
    event!(TYPE_URL_GET_RESPONSE, GetResponse);
    command!(TYPE_URL_SET_REQUEST, SetRequest);
    command!(TYPE_URL_ADD_REQUEST, AddRequest);
    event!(TYPE_URL_ADD_RESPONSE, AddResponse);
    command!(TYPE_URL_LIST_PUSH_REQUEST, ListPushRequest);
    event!(TYPE_URL_LIST_RESPONSE, ListResponse);
    command!(TYPE_URL_LIST_CLEAR_REQUEST, ListClearRequest);
    command!(TYPE_URL_LIST_RANGE_REQUEST, ListRangeRequest);
    event!(TYPE_URL_LIST_RANGE_RESPONSE, ListRangeResponse);
    command!(TYPE_URL_DEL_REQUEST, DelRequest);

}

/// A trait that allows a protobuf message to be wrapped as a payload inside a command
pub trait AsCommand {
    fn as_command(&self, source: &str, target_cap: &str) -> crate::core::Command;
}

/// A trait that allows a protobuf message to be wrapped as a payload inside an event
pub trait AsEvent {
    fn as_event(&self, success: bool, error: Option<(i32, &str)>) -> crate::core::Event;
}

pub mod capabilities;

pub fn pack_any(msg: &impl prost::Message, type_url: &str) -> prost_types::Any {
    let mut v = Vec::with_capacity(msg.encoded_len());
    msg.encode(&mut v).unwrap();
    prost_types::Any {
        type_url: type_url.to_string(),
        value: v,
    }
}

/// Creates a new `Command` from any arbitrary protobuf message 
pub fn create_command(
    msg: &impl prost::Message,
    type_url: &str,
    source: &str,
    target_cap: &str,
) -> crate::core::Command {
    let any = pack_any(msg, type_url);

    crate::core::Command {
        source: source.to_string(),
        target_cap: target_cap.to_string(),
        payload: Some(any),
    }
}

/// Creates a new `Event` from any arbitrary protobuf message
pub fn create_event(
    msg: Option<&impl prost::Message>,
    type_url: &str,
    success: bool,
    error: Option<(i32, &str)>,
) -> crate::core::Event {
    let any = msg.map(|m| pack_any(m, type_url));

    crate::core::Event {
        success,
        payload: any,
        error: error.map(|(c, d)| crate::core::Error {
            description: d.to_string(),
            code: c,
        }),
    }
}