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
//! Wasmcloud Weld runtime library
//!
//! This crate provides code generation and runtime support for wasmcloud rpc messages
//! used by [wasmcloud](https://wasmcloud.dev) actors and capability providers.
//!
//#![feature(toowned_clone_into)]

mod timestamp;
pub use timestamp::Timestamp;

mod actor_wasm;
mod common;
pub use common::{
    context::Context, deserialize, serialize, Message, MessageDispatch, RpcError, SendOpts,
    Transport,
};
pub mod channel_log;
pub mod provider;
pub(crate) mod provider_main;
mod wasmbus_model;
pub mod model {
    // re-export core lib as "core"
    pub use crate::wasmbus_model::*;
}

#[cfg(not(target_arch = "wasm32"))]
pub(crate) mod rpc_client;
#[cfg(not(target_arch = "wasm32"))]
pub use rpc_client::{RpcClient, RpcClientSync};

pub type RpcResult<T> = std::result::Result<T, RpcError>;

/// Version number of this api
#[doc(hidden)]
pub const WASMBUS_RPC_VERSION: u32 = 0;

/// import module for webassembly linking
#[doc(hidden)]
pub const WASMBUS_RPC_IMPORT_NAME: &str = "wapc";

/// This crate's published version
pub const WELD_CRATE_VERSION: &str = env!("CARGO_PKG_VERSION");

pub type CallResult = std::result::Result<Vec<u8>, Box<dyn std::error::Error + Sync + Send>>;
pub type HandlerResult<T> = std::result::Result<T, Box<dyn std::error::Error + Sync + Send>>;
pub type TomlMap = toml::value::Map<String, toml::value::Value>;

mod wasmbus_core;
pub mod core {
    // re-export core lib as "core"
    pub use crate::wasmbus_core::*;
    use crate::RpcError;
    use std::convert::TryFrom;

    cfg_if::cfg_if! {
        if #[cfg(not(target_arch = "wasm32"))] {

            // allow testing provider outside host
            const TEST_HARNESS: &str = "_TEST_";

            /// how often we will ping nats server for keep-alive
            const NATS_PING_INTERVAL_SEC: u16 = 15;

            /// number of unsuccessful pings before connection is deemed disconnected
            const NATS_PING_FAIL_COUNT: u16 = 8;

            // TODO: is this milliseconds? - units not documented
            /// time between connection retries
            const NATS_RECONNECT_INTERVAL: u64 = 15;

            impl HostData {
                /// returns whether the provider is running under test
                pub fn is_test(&self) -> bool {
                    self.host_id == TEST_HARNESS
                }

                /// obtain NatsClientOptions pre-populated with connection data from the host.
                pub fn nats_options(&self) -> ratsio::NatsClientOptions {
                    ratsio::NatsClientOptions {
                        ping_interval: NATS_PING_INTERVAL_SEC,
                        ping_max_out: NATS_PING_FAIL_COUNT,
                        reconnect_timeout: NATS_RECONNECT_INTERVAL,
                        // if connect fails, keep trying, forever
                        ensure_connect: true,
                        // need to test whether this works
                        subscribe_on_reconnect: true,
                        cluster_uris: if self.lattice_rpc_url.is_empty() {
                            Vec::new()
                        } else {
                            vec![self.lattice_rpc_url.clone()]
                        }
                        .into(),
                        ..Default::default()
                    }
                }
            }
        }
    }

    /// url scheme for wasmbus protocol messages
    pub const URL_SCHEME: &str = "wasmbus";

    impl std::fmt::Display for WasmCloudEntity {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            write!(f, "{}", self.url())
        }
    }

    impl LinkDefinition {
        pub fn actor_entity(&self) -> WasmCloudEntity {
            WasmCloudEntity {
                public_key: self.actor_id.clone(),
                contract_id: String::default(),
                link_name: String::default(),
            }
        }
        pub fn provider_entity(&self) -> WasmCloudEntity {
            WasmCloudEntity {
                public_key: self.provider_id.clone(),
                contract_id: self.contract_id.clone(),
                link_name: self.link_name.clone(),
            }
        }
    }

    impl WasmCloudEntity {
        /// constructor for actor entity
        pub fn new_actor<T: ToString>(public_key: T) -> Result<WasmCloudEntity, RpcError> {
            let public_key = public_key.to_string();
            if public_key.is_empty() {
                return Err(RpcError::InvalidParameter(
                    "public_key may not be empty".to_string(),
                ));
            }
            Ok(WasmCloudEntity {
                public_key,
                contract_id: String::new(),
                link_name: String::new(),
            })
        }

        /*
        /// create provider entity from link definition
        pub fn from_link(link: &LinkDefinition) -> Self {
            WasmCloudEntity {
                public_key: link.provider_id.clone(),
                contract_id: link.contract_id.clone(),
                link_name: link.link_name.clone(),
            }
        }
         */

        /// constructor for capability provider entity
        /// all parameters are required
        pub fn new_provider<T1: ToString, T2: ToString>(
            contract_id: T1,
            link_name: T2,
        ) -> Result<WasmCloudEntity, RpcError> {
            let contract_id = contract_id.to_string();
            if contract_id.is_empty() {
                return Err(RpcError::InvalidParameter(
                    "contract_id may not be empty".to_string(),
                ));
            }
            let link_name = link_name.to_string();
            if link_name.is_empty() {
                return Err(RpcError::InvalidParameter(
                    "link_name may not be empty".to_string(),
                ));
            }
            Ok(WasmCloudEntity {
                public_key: "".to_string(),
                contract_id,
                link_name,
            })
        }

        /// Returns URL of the entity
        pub fn url(&self) -> String {
            if self.public_key.to_uppercase().starts_with('M') {
                format!("{}://{}", crate::core::URL_SCHEME, self.public_key)
            } else {
                format!(
                    "{}://{}/{}/{}",
                    URL_SCHEME,
                    self.contract_id
                        .replace(":", "/")
                        .replace(" ", "_")
                        .to_lowercase(),
                    self.link_name.replace(" ", "_").to_lowercase(),
                    self.public_key
                )
            }
        }

        /// Returns the unique (public) key of the entity
        pub fn public_key(&self) -> String {
            self.public_key.to_string()
        }

        /// returns true if this entity refers to an actor
        pub fn is_actor(&self) -> bool {
            self.link_name.is_empty() || self.contract_id.is_empty()
        }

        /// returns true if this entity refers to a provider
        pub fn is_provider(&self) -> bool {
            !self.is_actor()
        }
    }

    impl TryFrom<&str> for WasmCloudEntity {
        type Error = RpcError;
        /// converts string into actor entity
        fn try_from(target: &str) -> Result<WasmCloudEntity, Self::Error> {
            WasmCloudEntity::new_actor(target.to_string())
        }
    }

    impl TryFrom<String> for WasmCloudEntity {
        type Error = RpcError;
        /// converts string into actor entity
        fn try_from(target: String) -> Result<WasmCloudEntity, Self::Error> {
            WasmCloudEntity::new_actor(target)
        }
    }
}

pub mod actor {

    pub mod prelude {
        pub use crate::{
            core::{Actor, ActorReceiver},
            RpcResult, {Context, Message, MessageDispatch, RpcError},
        };

        // re-export async_trait
        pub use async_trait::async_trait;
        // derive macros
        pub use wasmbus_macros::{Actor, ActorHealthResponder as HealthResponder};

        #[cfg(feature = "BigInteger")]
        pub use num_bigint::BigInt as BigInteger;

        #[cfg(feature = "BigDecimal")]
        pub use bigdecimal::BigDecimal;

        cfg_if::cfg_if! {

            if #[cfg(target_arch = "wasm32")] {
                pub use crate::actor_wasm::{console_log, WasmHost};
            } else {
                // this code is non-functional, since actors only run in wasm32,
                // but it reduces compiler errors if you are building a cargo multi-project workspace for non-wasm32
                #[derive(Clone, Debug, Default)]
                pub struct WasmHost {}

                #[async_trait]
                impl crate::Transport for WasmHost {
                    async fn send(&self, _ctx: &Context,
                                _msg: Message<'_>, _opts: Option<crate::SendOpts> ) -> std::result::Result<Vec<u8>, RpcError> {
                       unimplemented!();
                    }
                }

                pub fn console_log(_s: &str) {}
            }
        }
    }
}