kube32_sdk/lib.rs
1//! Rust bindings for the Kube32 WebAssembly pod ABI.
2//!
3//! A request-handling pod is a few functions and one macro invocation:
4//!
5//! ```ignore
6//! #![no_std]
7//! use kube32_sdk::{kube32_app, Request, Response};
8//!
9//! fn handle(req: &Request) -> i32 {
10//! let mut resp = Response::json(200);
11//! resp.write_str("{\"path\":").write_json_str(req.path).write_str("}");
12//! resp.end()
13//! }
14//!
15//! kube32_app! { handle: handle, }
16//! ```
17//!
18//! The macro exports `k32_alloc` and `k32_handle` (plus `k32_init`,
19//! `k32_tick`, `k32_event` when given); the host looks them up by name
20//! (`include/runtime/k32_app_abi.h`). Build with
21//! `cargo build --release --target wasm32-unknown-unknown` and the link flags
22//! in `sdk/rust/.cargo/config.toml`, or with `tools/kube32-cli build`.
23//!
24//! The crate is `no_std`; the only allocation is the static request buffer
25//! the macro reserves for `k32_alloc`.
26//!
27//! Features:
28//!
29//! * `panic-handler` (default): a `#[panic_handler]` that logs through
30//! `k32_log` and traps.
31//! * `hardware`: [`hardware`] wraps `k32_display_*`, `k32_key_read`,
32//! `k32_tone` and the infrared imports `esp32_rmt_send` and
33//! `esp32_rmt_receive`.
34//! * `fs`: [`fs`] wraps the `k32_fs_*` imports (pod storage on the microSD card).
35//! * `linalg`: [`linalg`] wraps the native products for quantized neural
36//! networks (`k32_matvec_*`, `k32_matmul_*`, `k32_vecmat_f32_i8`,
37//! `k32_softmax_f32`) and their element-wise steps (`k32_rmsnorm_f32`,
38//! `k32_quantize_i8`, `k32_rope_f32`, `k32_swiglu_f32`, `k32_add_f32`,
39//! `k32_argmax_f32`).
40//!
41//! An import is only linked into the module when the app calls it, so the
42//! module's import list tells which manifest resources it needs;
43//! `tools/kube32-cli check` prints that list.
44#![no_std]
45#![allow(clippy::needless_doctest_main)]
46
47pub mod abi;
48pub mod buf;
49pub mod channel;
50#[cfg(feature = "fs")]
51pub mod fs;
52#[cfg(feature = "hardware")]
53pub mod hardware;
54#[cfg(feature = "linalg")]
55pub mod linalg;
56pub mod host;
57pub mod request;
58pub mod response;
59
60pub use buf::Buf;
61pub use channel::Channel;
62pub use host::{delay_ms, emit, env, env_len, env_u32, log, mem_stats, random, time_ms};
63pub use request::{parse_u32, percent_decode, Request};
64pub use response::Response;
65
66/// `k32_handle` return value when the request block could not be parsed.
67pub const HANDLE_ERR_NO_RESPONSE: i32 = -1;
68pub const HANDLE_ERR_BAD_REQUEST: i32 = -2;
69
70/// Limits enforced by the host (`k32_app_abi.h`).
71pub const MAX_REQUEST_BYTES: usize = 16 * 1024;
72pub const MAX_EVENT_BYTES: usize = 200;
73pub const MAX_HEADER_BYTES: usize = 256;
74
75/// Host error codes: negative errno values (`k32_app_abi.h`, `hal_types.hpp`).
76pub const ERR_PERM: i32 = -1;
77pub const ERR_NOENT: i32 = -2;
78pub const ERR_IO: i32 = -5;
79pub const ERR_TOOBIG: i32 = -7;
80pub const ERR_BADF: i32 = -9;
81pub const ERR_AGAIN: i32 = -11;
82pub const ERR_NOMEM: i32 = -12;
83pub const ERR_FAULT: i32 = -14;
84pub const ERR_EXIST: i32 = -17;
85pub const ERR_NODEV: i32 = -19;
86pub const ERR_ISDIR: i32 = -21;
87pub const ERR_INVAL: i32 = -22;
88pub const ERR_MFILE: i32 = -24;
89pub const ERR_NOSPC: i32 = -28;
90pub const ERR_NAMETOOLONG: i32 = -36;
91/// `kube32_channel_recv` when nothing arrived in time.
92pub const ERR_TIMEDOUT: i32 = -110;
93
94#[derive(Clone, Copy, Debug, PartialEq, Eq)]
95pub enum Error {
96 /// The manifest does not grant the capability (`K32_ERR_PERM`); the host logs a violation.
97 Permission,
98 /// No such file or directory (`K32_ERR_NOENT`).
99 NotFound,
100 /// I/O error on the card or the radio (`K32_ERR_IO`).
101 Io,
102 /// The data does not fit the buffer (`K32_ERR_TOOBIG`): an IR frame
103 /// longer than the buffer, whose first part was copied.
104 TooBig,
105 /// File descriptor not open, or opened for the other direction (`K32_ERR_BADF`).
106 BadFd,
107 /// Pointer or length outside linear memory (`K32_ERR_FAULT`).
108 Fault,
109 /// `O_EXCL` and the file exists (`K32_ERR_EXIST`).
110 Exists,
111 /// No such device on this node (`K32_ERR_NODEV`): no card, or no display on the simulator.
112 NoDevice,
113 /// The path names a directory (`K32_ERR_ISDIR`).
114 IsDir,
115 /// Bad argument: bad path or flags, oversized payload (`K32_ERR_INVAL`).
116 Invalid,
117 /// Four files already open, per pod or node-wide (`K32_ERR_MFILE`).
118 TooManyFiles,
119 /// Card full (`K32_ERR_NOSPC`).
120 NoSpace,
121 /// Path longer than 96 bytes (`K32_ERR_NAMETOOLONG`).
122 NameTooLong,
123 /// Any other negative code from the host.
124 Host(i32),
125}
126
127impl Error {
128 /// Maps a host return code: negative codes become errors, others are returned.
129 pub fn from_rc(rc: i32) -> Result<u32, Error> {
130 match rc {
131 n if n >= 0 => Ok(n as u32),
132 ERR_PERM => Err(Error::Permission),
133 ERR_NOENT => Err(Error::NotFound),
134 ERR_IO => Err(Error::Io),
135 ERR_TOOBIG => Err(Error::TooBig),
136 ERR_BADF => Err(Error::BadFd),
137 ERR_FAULT => Err(Error::Fault),
138 ERR_EXIST => Err(Error::Exists),
139 ERR_NODEV => Err(Error::NoDevice),
140 ERR_ISDIR => Err(Error::IsDir),
141 ERR_INVAL => Err(Error::Invalid),
142 ERR_MFILE => Err(Error::TooManyFiles),
143 ERR_NOSPC => Err(Error::NoSpace),
144 ERR_NAMETOOLONG => Err(Error::NameTooLong),
145 n => Err(Error::Host(n)),
146 }
147 }
148
149 /// The host's code for this error.
150 pub fn code(self) -> i32 {
151 match self {
152 Error::Permission => ERR_PERM,
153 Error::NotFound => ERR_NOENT,
154 Error::Io => ERR_IO,
155 Error::TooBig => ERR_TOOBIG,
156 Error::BadFd => ERR_BADF,
157 Error::Fault => ERR_FAULT,
158 Error::Exists => ERR_EXIST,
159 Error::NoDevice => ERR_NODEV,
160 Error::IsDir => ERR_ISDIR,
161 Error::Invalid => ERR_INVAL,
162 Error::TooManyFiles => ERR_MFILE,
163 Error::NoSpace => ERR_NOSPC,
164 Error::NameTooLong => ERR_NAMETOOLONG,
165 Error::Host(n) => n,
166 }
167 }
168}
169
170#[cfg(test)]
171mod tests {
172 use super::*;
173
174 #[test]
175 fn host_codes_map_to_errors_and_back() {
176 let all = [
177 Error::Permission,
178 Error::NotFound,
179 Error::Io,
180 Error::TooBig,
181 Error::BadFd,
182 Error::Fault,
183 Error::Exists,
184 Error::NoDevice,
185 Error::IsDir,
186 Error::Invalid,
187 Error::TooManyFiles,
188 Error::NoSpace,
189 Error::NameTooLong,
190 ];
191 for e in all {
192 assert_eq!(Error::from_rc(e.code()), Err(e));
193 }
194 assert_eq!(Error::from_rc(ERR_TOOBIG), Err(Error::TooBig));
195 assert_eq!(Error::from_rc(67), Ok(67));
196 assert_eq!(Error::from_rc(ERR_AGAIN), Err(Error::Host(ERR_AGAIN)));
197 }
198}
199
200/// Default size of the buffer `k32_alloc` hands to the host: one maximal
201/// request block (16 KiB) plus room for an event topic and payload.
202pub const DEFAULT_ALLOC_BYTES: usize = MAX_REQUEST_BYTES + 512;
203
204#[doc(hidden)]
205#[macro_export]
206macro_rules! __k32_alloc_bytes {
207 () => {
208 $crate::DEFAULT_ALLOC_BYTES
209 };
210 ($e:expr) => {
211 $e
212 };
213}
214
215/// Exports the request-pod entry points. Keys are optional but must appear
216/// in this order: `alloc` (buffer size in bytes), `init`, `handle`, `tick`,
217/// `event`.
218///
219/// ```ignore
220/// kube32_app! {
221/// alloc: 4096, // optional, default DEFAULT_ALLOC_BYTES
222/// init: init, // fn() -> i32
223/// handle: handle, // fn(&Request) -> i32
224/// tick: tick, // fn(uptime_ms: u32) -> i32 (1 when more work is pending)
225/// event: on_event, // fn(topic: &str, data: &[u8]) -> i32
226/// }
227/// ```
228#[macro_export]
229macro_rules! kube32_app {
230 (
231 $(alloc: $alloc:expr,)?
232 $(init: $init:path,)?
233 $(handle: $handle:path,)?
234 $(tick: $tick:path,)?
235 $(event: $event:path,)?
236 ) => {
237 const __K32_ALLOC_BYTES: usize = $crate::__k32_alloc_bytes!($($alloc)?);
238 static mut __K32_ALLOC_BUF: [u8; __K32_ALLOC_BYTES] = [0; __K32_ALLOC_BYTES];
239
240 /// The host copies each request or event here before calling the handler.
241 #[no_mangle]
242 pub extern "C" fn k32_alloc(size: u32) -> u32 {
243 if size as usize > __K32_ALLOC_BYTES {
244 return 0;
245 }
246 unsafe { ::core::ptr::addr_of_mut!(__K32_ALLOC_BUF) as *mut u8 as u32 }
247 }
248
249 $(
250 #[no_mangle]
251 pub extern "C" fn k32_init() -> i32 {
252 let f: fn() -> i32 = $init;
253 f()
254 }
255 )?
256
257 $(
258 #[no_mangle]
259 pub extern "C" fn k32_handle(ptr: u32, len: u32) -> i32 {
260 let block: &[u8] = unsafe { ::core::slice::from_raw_parts(ptr as *const u8, len as usize) };
261 let f: fn(&$crate::Request) -> i32 = $handle;
262 match $crate::Request::parse(block) {
263 Some(req) => f(&req),
264 // Not a request line we can read (no method, non-ASCII):
265 // answer instead of letting the host turn silence into a 500.
266 None => {
267 let mut resp = $crate::Response::text(400);
268 resp.write_str("bad request\n");
269 resp.end()
270 }
271 }
272 }
273 )?
274
275 $(
276 #[no_mangle]
277 pub extern "C" fn k32_tick(uptime_ms: u32) -> i32 {
278 let f: fn(u32) -> i32 = $tick;
279 f(uptime_ms)
280 }
281 )?
282
283 $(
284 #[no_mangle]
285 pub extern "C" fn k32_event(topic_ptr: u32, topic_len: u32, ptr: u32, len: u32) -> i32 {
286 let topic: &[u8] = unsafe { ::core::slice::from_raw_parts(topic_ptr as *const u8, topic_len as usize) };
287 let data: &[u8] = unsafe { ::core::slice::from_raw_parts(ptr as *const u8, len as usize) };
288 let f: fn(&str, &[u8]) -> i32 = $event;
289 // Topics are channel names such as "counter.events": ASCII.
290 let topic = if topic.is_ascii() { unsafe { ::core::str::from_utf8_unchecked(topic) } } else { "" };
291 f(topic, data)
292 }
293 )?
294 };
295}
296
297/// Exports `app_main` for a pod that runs its own loop (display, keyboard,
298/// channels) instead of handling requests. The host runs it on the pod's own
299/// thread; returning ends the container (the pod log says
300/// `entrypoint returned, container completed`). The return value is not used.
301///
302/// ```ignore
303/// fn main_loop() -> i32 { loop { /* ... */ } }
304/// kube32_main!(main_loop);
305/// ```
306#[macro_export]
307macro_rules! kube32_main {
308 ($main:path) => {
309 #[no_mangle]
310 pub extern "C" fn app_main() -> i32 {
311 let f: fn() -> i32 = $main;
312 f()
313 }
314 };
315}
316
317#[cfg(all(target_arch = "wasm32", feature = "panic-handler"))]
318#[panic_handler]
319fn panic(_info: &core::panic::PanicInfo) -> ! {
320 host::log("[rust] panic: guest trapped");
321 core::arch::wasm32::unreachable()
322}