wasmcloud_actor_telnet/
generated.rs

1extern crate rmp_serde as rmps;
2use rmps::{Deserializer, Serializer};
3use serde::{Deserialize, Serialize};
4use std::io::Cursor;
5
6#[cfg(feature = "guest")]
7extern crate wapc_guest as guest;
8#[cfg(feature = "guest")]
9use guest::prelude::*;
10
11#[cfg(feature = "guest")]
12use lazy_static::lazy_static;
13#[cfg(feature = "guest")]
14use std::sync::RwLock;
15
16#[cfg(feature = "guest")]
17pub struct Host {
18    binding: String,
19}
20
21#[cfg(feature = "guest")]
22impl Default for Host {
23    fn default() -> Self {
24        Host {
25            binding: "default".to_string(),
26        }
27    }
28}
29
30/// Creates a named host binding for the telnet capability
31#[cfg(feature = "guest")]
32pub fn host(binding: &str) -> Host {
33    Host {
34        binding: binding.to_string(),
35    }
36}
37
38/// Creates the default host binding for the telnet capability
39#[cfg(feature = "guest")]
40pub fn default() -> Host {
41    Host::default()
42}
43
44#[cfg(feature = "guest")]
45impl Host {
46    /// Sends a string of text to a given session. The provider is not responsible for
47    /// indicating if this is a valid session or not. The telnet provider will not automatically
48    /// add newlines or carriage returns.
49    pub fn send_text(&self, session: String, text: String) -> HandlerResult<TelnetResult> {
50        let input_args = SendTextArgs { session, text };
51        host_call(
52            &self.binding,
53            "wasmcloud:telnet",
54            "SendText",
55            &serialize(input_args)?,
56        )
57        .map(|vec| {
58            let resp = deserialize::<TelnetResult>(vec.as_ref()).unwrap();
59            resp
60        })
61        .map_err(|e| e.into())
62    }
63}
64
65#[cfg(feature = "guest")]
66pub struct Handlers {}
67
68#[cfg(feature = "guest")]
69impl Handlers {
70    /// Register a function to receive session information when a user connects
71    /// to the linked telnet provider
72    pub fn register_session_started(f: fn(String) -> HandlerResult<TelnetResult>) {
73        *SESSION_STARTED.write().unwrap() = Some(f);
74        register_function(&"SessionStarted", session_started_wrapper);
75    }
76    /// Register a function to handle text received from the linked telnet provider
77    pub fn register_receive_text(f: fn(String, String) -> HandlerResult<TelnetResult>) {
78        *RECEIVE_TEXT.write().unwrap() = Some(f);
79        register_function(&"ReceiveText", receive_text_wrapper);
80    }
81}
82
83#[cfg(feature = "guest")]
84lazy_static! {
85    static ref SESSION_STARTED: RwLock<Option<fn(String) -> HandlerResult<TelnetResult>>> =
86        RwLock::new(None);
87    static ref RECEIVE_TEXT: RwLock<Option<fn(String, String) -> HandlerResult<TelnetResult>>> =
88        RwLock::new(None);
89}
90
91#[cfg(feature = "guest")]
92fn session_started_wrapper(input_payload: &[u8]) -> CallResult {
93    let input = deserialize::<SessionStartedArgs>(input_payload)?;
94    let lock = SESSION_STARTED.read().unwrap().unwrap();
95    let result = lock(input.session)?;
96    Ok(serialize(result)?)
97}
98
99#[cfg(feature = "guest")]
100fn receive_text_wrapper(input_payload: &[u8]) -> CallResult {
101    let input = deserialize::<ReceiveTextArgs>(input_payload)?;
102    let lock = RECEIVE_TEXT.read().unwrap().unwrap();
103    let result = lock(input.session, input.text)?;
104    Ok(serialize(result)?)
105}
106
107#[derive(Debug, PartialEq, Deserialize, Serialize, Default, Clone)]
108pub struct SessionStartedArgs {
109    #[serde(rename = "session")]
110    pub session: String,
111}
112
113#[derive(Debug, PartialEq, Deserialize, Serialize, Default, Clone)]
114pub struct ReceiveTextArgs {
115    #[serde(rename = "session")]
116    pub session: String,
117    #[serde(rename = "text")]
118    pub text: String,
119}
120
121#[derive(Debug, PartialEq, Deserialize, Serialize, Default, Clone)]
122pub struct SendTextArgs {
123    #[serde(rename = "session")]
124    pub session: String,
125    #[serde(rename = "text")]
126    pub text: String,
127}
128
129#[derive(Debug, PartialEq, Deserialize, Serialize, Default, Clone)]
130pub struct TelnetResult {
131    #[serde(rename = "success")]
132    pub success: bool,
133    #[serde(rename = "error")]
134    pub error: Option<String>,
135}
136
137/// The standard function for serializing codec structs into a format that can be
138/// used for message exchange between actor and host. Use of any other function to
139/// serialize could result in breaking incompatibilities.
140pub fn serialize<T>(
141    item: T,
142) -> ::std::result::Result<Vec<u8>, Box<dyn std::error::Error + Send + Sync>>
143where
144    T: Serialize,
145{
146    let mut buf = Vec::new();
147    item.serialize(&mut Serializer::new(&mut buf).with_struct_map())?;
148    Ok(buf)
149}
150
151/// The standard function for de-serializing codec structs from a format suitable
152/// for message exchange between actor and host. Use of any other function to
153/// deserialize could result in breaking incompatibilities.
154pub fn deserialize<'de, T: Deserialize<'de>>(
155    buf: &[u8],
156) -> ::std::result::Result<T, Box<dyn std::error::Error + Send + Sync>> {
157    let mut de = Deserializer::new(Cursor::new(buf));
158    match Deserialize::deserialize(&mut de) {
159        Ok(t) => Ok(t),
160        Err(e) => Err(format!("Failed to de-serialize: {}", e).into()),
161    }
162}