actor_interfaces/
ui.rs

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
// This file is @generated by wasmcloud/weld-codegen 0.7.0.
// It is not intended for manual editing.
// namespace: jclmnop.iiot_poc.interface.ui

#[allow(unused_imports)]
use async_trait::async_trait;
#[allow(unused_imports)]
use serde::{Deserialize, Serialize};
#[allow(unused_imports)]
use std::{borrow::Borrow, borrow::Cow, io::Write, string::ToString};
#[allow(unused_imports)]
use wasmbus_rpc::{
    cbor::*,
    common::{
        deserialize, message_format, serialize, Context, Message, MessageDispatch, MessageFormat,
        SendOpts, Transport,
    },
    error::{RpcError, RpcResult},
    Timestamp,
};

#[allow(dead_code)]
pub const SMITHY_VERSION: &str = "1.0";

#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
pub struct GetAssetResponse {
    /// Raw asset as bytes.
    #[serde(with = "serde_bytes")]
    #[serde(default)]
    pub asset: Vec<u8>,
    /// Optional hint to the caller about the content type of the asset. Should be a valid MIME type.
    #[serde(rename = "contentType")]
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub content_type: Option<String>,
    /// True if request was successful and asset was found, false if request was successful but asset was not found.
    #[serde(default)]
    pub found: bool,
}

// Encode GetAssetResponse as CBOR and append to output stream
#[doc(hidden)]
#[allow(unused_mut)]
pub fn encode_get_asset_response<W: wasmbus_rpc::cbor::Write>(
    mut e: &mut wasmbus_rpc::cbor::Encoder<W>,
    val: &GetAssetResponse,
) -> RpcResult<()>
where
    <W as wasmbus_rpc::cbor::Write>::Error: std::fmt::Display,
{
    e.map(3)?;
    e.str("asset")?;
    e.bytes(&val.asset)?;
    if let Some(val) = val.content_type.as_ref() {
        e.str("contentType")?;
        e.str(val)?;
    } else {
        e.null()?;
    }
    e.str("found")?;
    e.bool(val.found)?;
    Ok(())
}

// Decode GetAssetResponse from cbor input stream
#[doc(hidden)]
pub fn decode_get_asset_response(
    d: &mut wasmbus_rpc::cbor::Decoder<'_>,
) -> Result<GetAssetResponse, RpcError> {
    let __result = {
        let mut asset: Option<Vec<u8>> = None;
        let mut content_type: Option<Option<String>> = Some(None);
        let mut found: Option<bool> = None;

        let is_array = match d.datatype()? {
            wasmbus_rpc::cbor::Type::Array => true,
            wasmbus_rpc::cbor::Type::Map => false,
            _ => {
                return Err(RpcError::Deser(
                    "decoding struct GetAssetResponse, expected array or map".to_string(),
                ))
            }
        };
        if is_array {
            let len = d.fixed_array()?;
            for __i in 0..(len as usize) {
                match __i {
                    0 => asset = Some(d.bytes()?.to_vec()),
                    1 => {
                        content_type = if wasmbus_rpc::cbor::Type::Null == d.datatype()? {
                            d.skip()?;
                            Some(None)
                        } else {
                            Some(Some(d.str()?.to_string()))
                        }
                    }
                    2 => found = Some(d.bool()?),
                    _ => d.skip()?,
                }
            }
        } else {
            let len = d.fixed_map()?;
            for __i in 0..(len as usize) {
                match d.str()? {
                    "asset" => asset = Some(d.bytes()?.to_vec()),
                    "contentType" => {
                        content_type = if wasmbus_rpc::cbor::Type::Null == d.datatype()? {
                            d.skip()?;
                            Some(None)
                        } else {
                            Some(Some(d.str()?.to_string()))
                        }
                    }
                    "found" => found = Some(d.bool()?),
                    _ => d.skip()?,
                }
            }
        }
        GetAssetResponse {
            asset: if let Some(__x) = asset {
                __x
            } else {
                return Err(RpcError::Deser(
                    "missing field GetAssetResponse.asset (#0)".to_string(),
                ));
            },
            content_type: content_type.unwrap(),

            found: if let Some(__x) = found {
                __x
            } else {
                return Err(RpcError::Deser(
                    "missing field GetAssetResponse.found (#2)".to_string(),
                ));
            },
        }
    };
    Ok(__result)
}
/// wasmbus.actorReceive
#[async_trait]
pub trait Ui {
    /// Gets the asset with the given path, for example `/index.html`.
    async fn get_asset<TS: ToString + ?Sized + std::marker::Sync>(
        &self,
        ctx: &Context,
        arg: &TS,
    ) -> RpcResult<GetAssetResponse>;
}

/// UiReceiver receives messages defined in the Ui service trait
#[doc(hidden)]
#[async_trait]
pub trait UiReceiver: MessageDispatch + Ui {
    async fn dispatch(&self, ctx: &Context, message: Message<'_>) -> Result<Vec<u8>, RpcError> {
        match message.method {
            "GetAsset" => {
                let value: String = wasmbus_rpc::common::deserialize(&message.arg)
                    .map_err(|e| RpcError::Deser(format!("'String': {}", e)))?;

                let resp = Ui::get_asset(self, ctx, &value).await?;
                let buf = wasmbus_rpc::common::serialize(&resp)?;

                Ok(buf)
            }
            _ => Err(RpcError::MethodNotHandled(format!(
                "Ui::{}",
                message.method
            ))),
        }
    }
}

/// UiSender sends messages to a Ui service
/// client for sending Ui messages
#[derive(Clone, Debug)]
pub struct UiSender<T: Transport> {
    transport: T,
}

impl<T: Transport> UiSender<T> {
    /// Constructs a UiSender with the specified transport
    pub fn via(transport: T) -> Self {
        Self { transport }
    }

    pub fn set_timeout(&self, interval: std::time::Duration) {
        self.transport.set_timeout(interval);
    }
}

#[cfg(not(target_arch = "wasm32"))]
impl<'send> UiSender<wasmbus_rpc::provider::ProviderTransport<'send>> {
    /// Constructs a Sender using an actor's LinkDefinition,
    /// Uses the provider's HostBridge for rpc
    pub fn for_actor(ld: &'send wasmbus_rpc::core::LinkDefinition) -> Self {
        Self {
            transport: wasmbus_rpc::provider::ProviderTransport::new(ld, None),
        }
    }
}
#[cfg(target_arch = "wasm32")]
impl UiSender<wasmbus_rpc::actor::prelude::WasmHost> {
    /// Constructs a client for actor-to-actor messaging
    /// using the recipient actor's public key
    pub fn to_actor(actor_id: &str) -> Self {
        let transport =
            wasmbus_rpc::actor::prelude::WasmHost::to_actor(actor_id.to_string()).unwrap();
        Self { transport }
    }
}
#[async_trait]
impl<T: Transport + std::marker::Sync + std::marker::Send> Ui for UiSender<T> {
    #[allow(unused)]
    /// Gets the asset with the given path, for example `/index.html`.
    async fn get_asset<TS: ToString + ?Sized + std::marker::Sync>(
        &self,
        ctx: &Context,
        arg: &TS,
    ) -> RpcResult<GetAssetResponse> {
        let buf = wasmbus_rpc::common::serialize(&arg.to_string())?;

        let resp = self
            .transport
            .send(
                ctx,
                Message {
                    method: "Ui.GetAsset",
                    arg: Cow::Borrowed(&buf),
                },
                None,
            )
            .await?;

        let value: GetAssetResponse = wasmbus_rpc::common::deserialize(&resp)
            .map_err(|e| RpcError::Deser(format!("'{}': GetAssetResponse", e)))?;
        Ok(value)
    }
}