Skip to main content

pulzr_package/
lib.rs

1//! Write a Pulzr extension module in Rust.
2//!
3//! An extension module is code a third party adds to the Pulzr platform, run
4//! in the platform's WebAssembly sandbox: a gateway support package's adapter
5//! (another vendor's gateway, translated into protocol v1) or a carrier driver.
6//! This crate hides the ABI ([`abi`], `docs/src/content/docs/abi.md`): implement [`Package`],
7//! name your type in [`export!`], and build for `wasm32-unknown-unknown`.
8//!
9//! ```no_run
10//! use pulzr_package::{export, Answer, Event, Package};
11//!
12//! #[derive(Default)]
13//! struct Hello;
14//!
15//! impl Package for Hello {
16//!     fn handle(&mut self, event: Event) -> Answer {
17//!         let mut answer = Answer::default();
18//!         if let Event::Tick { .. } = event {
19//!             answer.log_info("still here");
20//!         }
21//!         answer
22//!     }
23//! }
24//!
25//! export!(Hello);
26//! ```
27//!
28//! The host functions ([`host`]) are imported only when called, and each must
29//! be declared in the manifest's `imports`; [`ids`], [`hexs`], [`correlation`]
30//! and [`settings`] are the helpers gateway translators keep needing.
31
32pub mod abi;
33pub mod correlation;
34pub mod host;
35pub mod ids;
36pub mod settings;
37pub mod v1;
38
39/// The JSON library events and answers are made with, for a module's own parsing.
40pub use serde_json;
41pub use serde_json::{json, Map, Value};
42
43use base64::Engine as _;
44use serde::Serialize;
45
46/// The ABI version this crate's exports implement.
47pub const ABI_VERSION: i32 = 2;
48
49/// One event from the host. Gateway packages receive the first three; a kind
50/// with other events (a carrier driver's) reads them from [`Event::Other`].
51#[derive(Debug, Clone, PartialEq)]
52pub enum Event {
53    /// A vendor message on one of the package's broker subscriptions.
54    Message {
55        topic: String,
56        payload: Vec<u8>,
57        received: f64,
58    },
59    /// A protocol v1 intent for one of the package's gateways, its secret
60    /// params opened for this call.
61    Intent {
62        adapter: String,
63        key: String,
64        id: String,
65        name: String,
66        params: Value,
67        expires: Option<f64>,
68        now: f64,
69    },
70    /// About every ten seconds.
71    Tick { now: f64 },
72    /// An event of another kind, whole.
73    Other(Value),
74}
75
76impl Event {
77    /// Reads an event object; anything not one of the gateway events above is
78    /// [`Event::Other`].
79    pub fn from_value(v: Value) -> Event {
80        let s = |k: &str| v.get(k).and_then(Value::as_str).map(str::to_owned);
81        let f = |k: &str| v.get(k).and_then(Value::as_f64);
82        match v.get("event").and_then(Value::as_str) {
83            Some("message") => match (s("topic"), s("payload"), f("received")) {
84                (Some(topic), Some(p), Some(received)) => match hexs::b64_decode(&p) {
85                    Some(payload) => Event::Message {
86                        topic,
87                        payload,
88                        received,
89                    },
90                    None => Event::Other(v),
91                },
92                _ => Event::Other(v),
93            },
94            Some("intent") => match (s("adapter"), s("key"), s("id"), s("name"), f("now")) {
95                (Some(adapter), Some(key), Some(id), Some(name), Some(now)) => Event::Intent {
96                    adapter,
97                    key,
98                    id,
99                    name,
100                    now,
101                    params: v
102                        .get("params")
103                        .cloned()
104                        .unwrap_or_else(|| Value::Object(Map::new())),
105                    expires: f("expires"),
106                },
107                _ => Event::Other(v),
108            },
109            Some("tick") => match f("now") {
110                Some(now) => Event::Tick { now },
111                None => Event::Other(v),
112            },
113            _ => Event::Other(v),
114        }
115    }
116}
117
118/// A vendor message to publish.
119#[derive(Debug, Clone, PartialEq, Serialize)]
120pub struct Publish {
121    pub topic: String,
122    /// Base64 of the payload.
123    pub payload: String,
124}
125
126/// A protocol v1 message, as an adapter would publish it on
127/// `pulzr/a/<adapter>/d/<key>/<kind>`.
128#[derive(Debug, Clone, PartialEq, Serialize)]
129pub struct Protocol {
130    pub adapter: String,
131    pub key: String,
132    /// `up`, `state`, `settings`, `event` or `cmd/res`.
133    pub kind: String,
134    pub body: Value,
135}
136
137/// A line for the platform's log.
138#[derive(Debug, Clone, PartialEq, Serialize)]
139pub struct LogLine {
140    pub level: &'static str,
141    pub message: String,
142}
143
144/// The answer to one event. Every part is optional; `extra` carries a kind's
145/// own members (a carrier driver's).
146#[derive(Debug, Clone, Default, PartialEq, Serialize)]
147pub struct Answer {
148    #[serde(skip_serializing_if = "Vec::is_empty")]
149    pub publish: Vec<Publish>,
150    #[serde(skip_serializing_if = "Vec::is_empty")]
151    pub protocol: Vec<Protocol>,
152    #[serde(skip_serializing_if = "Vec::is_empty")]
153    pub log: Vec<LogLine>,
154    #[serde(flatten)]
155    pub extra: Map<String, Value>,
156}
157
158impl Answer {
159    /// Publish `payload` on a vendor topic.
160    pub fn publish(&mut self, topic: impl Into<String>, payload: impl AsRef<[u8]>) -> &mut Self {
161        self.publish.push(Publish {
162            topic: topic.into(),
163            payload: hexs::b64_encode(payload.as_ref()),
164        });
165        self
166    }
167
168    /// Publish a JSON value on a vendor topic.
169    pub fn publish_json(&mut self, topic: impl Into<String>, value: &Value) -> &mut Self {
170        self.publish(topic, value.to_string())
171    }
172
173    /// A protocol v1 message for `key` behind `adapter`.
174    pub fn protocol(
175        &mut self,
176        adapter: impl Into<String>,
177        key: impl Into<String>,
178        kind: &str,
179        body: Value,
180    ) -> &mut Self {
181        self.protocol.push(Protocol {
182            adapter: adapter.into(),
183            key: key.into(),
184            kind: kind.into(),
185            body,
186        });
187        self
188    }
189
190    /// The answer to an intent: `cmd/res` with its `id` and `status`.
191    pub fn result(&mut self, adapter: &str, key: &str, result: v1::CmdResult) -> &mut Self {
192        self.protocol(
193            adapter,
194            key,
195            "cmd/res",
196            serde_json::to_value(result).unwrap_or(Value::Null),
197        )
198    }
199
200    fn line(&mut self, level: &'static str, message: impl Into<String>) -> &mut Self {
201        self.log.push(LogLine {
202            level,
203            message: message.into(),
204        });
205        self
206    }
207
208    pub fn log_debug(&mut self, m: impl Into<String>) -> &mut Self {
209        self.line("debug", m)
210    }
211    pub fn log_info(&mut self, m: impl Into<String>) -> &mut Self {
212        self.line("info", m)
213    }
214    pub fn log_warning(&mut self, m: impl Into<String>) -> &mut Self {
215        self.line("warning", m)
216    }
217    pub fn log_error(&mut self, m: impl Into<String>) -> &mut Self {
218        self.line("error", m)
219    }
220}
221
222/// An extension module. One value lives for as long as its instance does:
223/// what it keeps may be lost at any time (a trap, an upgrade, a restart), so
224/// keep in it only what costs nothing to lose, and the rest in
225/// [`host::state_set`].
226pub trait Package: Default {
227    fn handle(&mut self, event: Event) -> Answer;
228}
229
230/// Hex and base64.
231pub mod hexs {
232    use super::*;
233
234    pub fn b64_encode(b: &[u8]) -> String {
235        base64::engine::general_purpose::STANDARD.encode(b)
236    }
237
238    pub fn b64_decode(s: &str) -> Option<Vec<u8>> {
239        base64::engine::general_purpose::STANDARD.decode(s).ok()
240    }
241
242    /// Lower-case hex.
243    pub fn encode(b: &[u8]) -> String {
244        b.iter().map(|x| format!("{x:02x}")).collect()
245    }
246
247    /// Hex of either case, or None.
248    pub fn decode(s: &str) -> Option<Vec<u8>> {
249        if s.len() % 2 != 0 || !s.is_ascii() {
250            return None;
251        }
252        (0..s.len())
253            .step_by(2)
254            .map(|i| u8::from_str_radix(&s[i..i + 2], 16).ok())
255            .collect()
256    }
257}
258
259/// Exports the ABI for a [`Package`] type: `pz_abi`, `pz_alloc`, `pz_handle`.
260#[macro_export]
261macro_rules! export {
262    ($t:ty) => {
263        ::std::thread_local! {
264            static PZ_PACKAGE: ::std::cell::RefCell<$t> = ::std::cell::RefCell::new(<$t>::default());
265        }
266
267        #[no_mangle]
268        pub extern "C" fn pz_abi() -> i32 {
269            $crate::ABI_VERSION
270        }
271
272        #[no_mangle]
273        pub extern "C" fn pz_alloc(len: i32) -> i32 {
274            $crate::abi::alloc(len)
275        }
276
277        #[no_mangle]
278        pub extern "C" fn pz_handle(ptr: i32, len: i32) -> i64 {
279            $crate::abi::handle(ptr, len, |event| PZ_PACKAGE.with(|p| p.borrow_mut().handle(event)))
280        }
281    };
282}
283
284#[cfg(test)]
285mod tests {
286    use super::*;
287
288    #[test]
289    fn events_are_read_and_answers_written() {
290        let e = Event::from_value(
291            json!({"event": "message", "topic": "t/1", "payload": "aGk=", "received": 5.0}),
292        );
293        assert_eq!(
294            e,
295            Event::Message {
296                topic: "t/1".into(),
297                payload: b"hi".to_vec(),
298                received: 5.0
299            }
300        );
301        let i = Event::from_value(
302            json!({"event": "intent", "adapter": "x-1", "key": "gw:1", "id": "7",
303                                         "name": "reboot", "now": 1.0, "expires": null}),
304        );
305        assert!(matches!(i, Event::Intent { ref name, expires: None, .. } if name == "reboot"));
306        assert!(matches!(
307            Event::from_value(json!({"event": "call", "x": 1})),
308            Event::Other(_)
309        ));
310        assert!(matches!(
311            Event::from_value(json!({"event": "message", "topic": "t"})),
312            Event::Other(_)
313        ));
314
315        let mut a = Answer::default();
316        a.publish("t/down", b"hi")
317            .protocol("x-1", "gw:1", "state", json!({"v": 1}))
318            .log_info("ok");
319        a.result("x-1", "gw:1", v1::CmdResult::ok("7"));
320        assert_eq!(
321            serde_json::to_value(&a).unwrap(),
322            json!({
323            "publish": [{"topic": "t/down", "payload": "aGk="}],
324            "protocol": [{"adapter": "x-1", "key": "gw:1", "kind": "state", "body": {"v": 1}},
325                         {"adapter": "x-1", "key": "gw:1", "kind": "cmd/res", "body": {"v": 1, "id": "7", "status": "ok"}}],
326            "log": [{"level": "info", "message": "ok"}]})
327        );
328        assert_eq!(serde_json::to_value(Answer::default()).unwrap(), json!({}));
329        assert_eq!(hexs::decode("0aFF"), Some(vec![10, 255]));
330        assert_eq!(hexs::encode(&[10, 255]), "0aff");
331        assert_eq!(hexs::decode("abc"), None);
332    }
333}