Skip to main content

cuttlefish_sdk/
lib.rs

1//! Guest-side library for writing cuttlefish proc-blocks.
2//!
3//! A block is a state machine that the host drives. It never calls the host and
4//! waits; it *returns* a [`Command`] saying what it wants, and the host — having
5//! done that thing — steps it again with an [`Event`]. See [`cuttlefish_abi`]
6//! for why control is inverted, and what that buys: chiefly that cancellation
7//! needs no cooperation from the guest, because the host simply stops stepping.
8//!
9//! This crate exists so block authors do not hand-write that inversion.
10//! Implement [`Block`], call [`export_block!`], and the macro emits the raw wasm
11//! exports the host expects.
12//!
13//! # Writing a block
14//!
15//! ```
16//! use cuttlefish_sdk::{Block, Command, Event};
17//!
18//! #[derive(Default)]
19//! struct Shout;
20//!
21//! impl Block for Shout {
22//!     fn start(&mut self, input: serde_json::Value) -> Command {
23//!         match input.get("path").and_then(|v| v.as_str()) {
24//!             Some(path) => Command::Open { path: path.to_string() },
25//!             None => Command::Fail {
26//!                 code: "schema_validation_failed".into(),
27//!                 message: "input needs a string `path`".into(),
28//!             },
29//!         }
30//!     }
31//!
32//!     fn step(&mut self, event: Event) -> Command {
33//!         match event {
34//!             Event::Opened { handle, len } => Command::Slice { handle, offset: 0, len },
35//!             Event::Sliced { text, .. } => Command::Done {
36//!                 result: serde_json::json!({ "shouted": text.to_uppercase() }),
37//!             },
38//!             other => Command::Fail {
39//!                 code: "unexpected_event".into(),
40//!                 message: format!("{other:?}"),
41//!             },
42//!         }
43//!     }
44//! }
45//!
46//! // A real block adds this to emit the wasm exports:
47//! //     cuttlefish_sdk::export_block!(Shout);
48//! ```
49//!
50//! Because a block is an ordinary Rust type, it can be unit-tested natively with
51//! no wasm involved: construct it, call `start`, then feed it the events its
52//! commands would produce. Only the boundary itself needs a wasm harness.
53//!
54//! # Memory ownership across the boundary
55//!
56//! Values handed to the host are leaked on purpose. The host reads them
57//! immediately after the call returns, and the entire instance is destroyed when
58//! the job ends, so there is nothing to reclaim and no cross-language allocator
59//! coordination to get wrong.
60//!
61//! Do not "fix" this by freeing. The host would then read freed memory, and on
62//! wasm that is a silent wrong answer rather than a segfault — the linear memory
63//! is still perfectly valid to read, it just no longer holds what anyone thinks.
64
65#![forbid(unsafe_op_in_unsafe_fn)]
66#![warn(missing_docs)]
67
68pub use cuttlefish_abi::{Command, Event, TokenAction};
69
70/// How a guest hands a (pointer, length) pair back to the host.
71///
72/// The obvious alternative is packing both into the single `i64` a wasm export
73/// can return. That works only while pointers are 32 bits. Returning a pointer
74/// to this struct instead costs one extra memory read per call and keeps every
75/// export signature unchanged under a 64-bit guest, where `usize` simply widens.
76///
77/// Do not replace this with bit-packing; that is precisely what it exists to
78/// avoid. The host reads exactly `2 * size_of::<usize>()` bytes at the returned
79/// address and splits them down the middle, so this layout is load-bearing —
80/// hence `#[repr(C)]`, and hence the tests pinning its size and field order.
81#[repr(C)]
82pub struct Desc {
83    /// Address of the payload.
84    pub ptr: usize,
85    /// Payload length, in bytes.
86    pub len: usize,
87}
88
89/// What a proc-block author implements.
90///
91/// The host calls [`start`](Block::start) once with the job's input, then
92/// [`step`](Block::step) after each command it carries out, until the block
93/// returns [`Command::Done`] or [`Command::Fail`].
94pub trait Block: Default {
95    /// Produce the first command from the job's input.
96    ///
97    /// Prefer returning [`Command::Fail`] to panicking on malformed input: a
98    /// panic becomes an opaque wasm trap, whereas a `Fail` carries a code and a
99    /// message the caller can act on.
100    fn start(&mut self, input: serde_json::Value) -> Command;
101
102    /// Produce the next command, given the result of the previous one.
103    fn step(&mut self, event: Event) -> Command;
104
105    /// Decide whether generation should continue, once per streamed token.
106    ///
107    /// Defaults to [`TokenAction::Continue`], so a block indifferent to
108    /// streaming can ignore it. A token or two may still arrive after returning
109    /// [`TokenAction::Stop`], because the verdict has to travel back to the
110    /// thread doing the generating.
111    fn on_token(&mut self, _token: &str) -> TokenAction {
112        TokenAction::Continue
113    }
114}
115
116/// Allocate a buffer for the host to write into, returning its address.
117///
118/// Leaked deliberately; see the crate docs on memory ownership.
119#[doc(hidden)]
120pub fn __alloc(len: usize) -> usize {
121    let mut buf = Vec::<u8>::with_capacity(len);
122    let ptr = buf.as_mut_ptr() as usize;
123    std::mem::forget(buf);
124    ptr
125}
126
127/// Decode JSON the host wrote at `ptr`.
128///
129/// # Safety
130///
131/// `ptr` must point at `len` initialized bytes written by the host, normally
132/// into a buffer obtained from [`__alloc`].
133#[doc(hidden)]
134pub unsafe fn __read_json<T: serde::de::DeserializeOwned>(ptr: usize, len: usize) -> T {
135    let slice = unsafe { std::slice::from_raw_parts(ptr as *const u8, len) };
136    serde_json::from_slice(slice).expect("host sent malformed JSON")
137}
138
139/// Serialize `value` into guest memory, returning the address of a [`Desc`]
140/// describing it.
141///
142/// Both the payload and the descriptor are leaked; see the crate docs.
143#[doc(hidden)]
144pub fn __write_json<T: serde::Serialize>(value: &T) -> usize {
145    let bytes = serde_json::to_vec(value).expect("guest produced unserializable value");
146    let len = bytes.len();
147    let ptr = Box::into_raw(bytes.into_boxed_slice()) as *mut u8 as usize;
148    Box::into_raw(Box::new(Desc { ptr, len })) as usize
149}
150
151/// Emit the wasm exports for a [`Block`] implementation.
152///
153/// The block's state lives in a thread-local because the host instantiates one
154/// module per job and never shares it — so there is exactly one block instance
155/// per module instance, and no cross-job state that could leak between them.
156///
157/// Every export takes and returns `usize` rather than a packed integer. On
158/// `wasm32` that lowers to `i32` parameters and results; on a 64-bit guest the
159/// same source compiles to `i64` with nothing here changing.
160#[macro_export]
161macro_rules! export_block {
162    ($ty:ty) => {
163        thread_local! {
164            static __CF_STATE: ::std::cell::RefCell<$ty> =
165                ::std::cell::RefCell::new(<$ty as ::core::default::Default>::default());
166        }
167
168        #[no_mangle]
169        pub extern "C" fn cf_alloc(len: usize) -> usize {
170            $crate::__alloc(len)
171        }
172
173        #[no_mangle]
174        pub extern "C" fn cf_init(ptr: usize, len: usize) -> usize {
175            let input: ::serde_json::Value = unsafe { $crate::__read_json(ptr, len) };
176            let cmd = __CF_STATE.with(|s| $crate::Block::start(&mut *s.borrow_mut(), input));
177            $crate::__write_json(&cmd)
178        }
179
180        #[no_mangle]
181        pub extern "C" fn cf_step(ptr: usize, len: usize) -> usize {
182            let event: $crate::Event = unsafe { $crate::__read_json(ptr, len) };
183            let cmd = __CF_STATE.with(|s| $crate::Block::step(&mut *s.borrow_mut(), event));
184            $crate::__write_json(&cmd)
185        }
186
187        #[no_mangle]
188        pub extern "C" fn cf_on_token(ptr: usize, len: usize) -> i32 {
189            // Lossy on purpose: a model can emit a token split mid-character,
190            // and mangling one character is a far better outcome than trapping
191            // the whole job over it.
192            let token: ::std::string::String = unsafe {
193                let slice = ::std::slice::from_raw_parts(ptr as *const u8, len);
194                ::std::string::String::from_utf8_lossy(slice).into_owned()
195            };
196            $crate::TokenAction::as_i32(
197                __CF_STATE.with(|s| $crate::Block::on_token(&mut *s.borrow_mut(), &token)),
198            )
199        }
200    };
201}