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, Handle, MediaKind, Signature, TokenAction, Ty};
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 /// What this block accepts and produces.
96 ///
97 /// Declared here rather than in a file beside the block, so it cannot
98 /// disagree with the code below it. The host reads this to typecheck a
99 /// pipeline's seams before running anything.
100 ///
101 /// The default is permissive — JSON in, JSON out — so an existing block
102 /// keeps working. That is deliberately the weakest useful answer: a pipeline
103 /// of `Json` seams typechecks unconditionally, so a block that means to be
104 /// composed should say something more specific.
105 fn signature() -> Signature {
106 Signature {
107 input: Ty::Json,
108 output: Ty::Json,
109 }
110 }
111
112 /// Produce the first command from the job's input.
113 ///
114 /// Prefer returning [`Command::Fail`] to panicking on malformed input: a
115 /// panic becomes an opaque wasm trap, whereas a `Fail` carries a code and a
116 /// message the caller can act on.
117 fn start(&mut self, input: serde_json::Value) -> Command;
118
119 /// Produce the next command, given the result of the previous one.
120 fn step(&mut self, event: Event) -> Command;
121
122 /// Decide whether generation should continue, once per streamed token.
123 ///
124 /// Defaults to [`TokenAction::Continue`], so a block indifferent to
125 /// streaming can ignore it. A token or two may still arrive after returning
126 /// [`TokenAction::Stop`], because the verdict has to travel back to the
127 /// thread doing the generating.
128 fn on_token(&mut self, _token: &str) -> TokenAction {
129 TokenAction::Continue
130 }
131}
132
133/// Allocate a buffer for the host to write into, returning its address.
134///
135/// Leaked deliberately; see the crate docs on memory ownership.
136#[doc(hidden)]
137pub fn __alloc(len: usize) -> usize {
138 let mut buf = Vec::<u8>::with_capacity(len);
139 let ptr = buf.as_mut_ptr() as usize;
140 std::mem::forget(buf);
141 ptr
142}
143
144/// Decode JSON the host wrote at `ptr`.
145///
146/// # Safety
147///
148/// `ptr` must point at `len` initialized bytes written by the host, normally
149/// into a buffer obtained from [`__alloc`].
150#[doc(hidden)]
151pub unsafe fn __read_json<T: serde::de::DeserializeOwned>(ptr: usize, len: usize) -> T {
152 let slice = unsafe { std::slice::from_raw_parts(ptr as *const u8, len) };
153 serde_json::from_slice(slice).expect("host sent malformed JSON")
154}
155
156/// Serialize `value` into guest memory, returning the address of a [`Desc`]
157/// describing it.
158///
159/// Both the payload and the descriptor are leaked; see the crate docs.
160#[doc(hidden)]
161pub fn __write_json<T: serde::Serialize>(value: &T) -> usize {
162 let bytes = serde_json::to_vec(value).expect("guest produced unserializable value");
163 let len = bytes.len();
164 let ptr = Box::into_raw(bytes.into_boxed_slice()) as *mut u8 as usize;
165 Box::into_raw(Box::new(Desc { ptr, len })) as usize
166}
167
168/// Emit the wasm exports for a [`Block`] implementation.
169///
170/// The block's state lives in a thread-local because the host instantiates one
171/// module per job and never shares it — so there is exactly one block instance
172/// per module instance, and no cross-job state that could leak between them.
173///
174/// Every export takes and returns `usize` rather than a packed integer. On
175/// `wasm32` that lowers to `i32` parameters and results; on a 64-bit guest the
176/// same source compiles to `i64` with nothing here changing.
177#[macro_export]
178macro_rules! export_block {
179 ($ty:ty) => {
180 thread_local! {
181 static __CF_STATE: ::std::cell::RefCell<$ty> =
182 ::std::cell::RefCell::new(<$ty as ::core::default::Default>::default());
183 }
184
185 #[no_mangle]
186 pub extern "C" fn cf_alloc(len: usize) -> usize {
187 $crate::__alloc(len)
188 }
189
190 /// Report this block's type signature. Read at build time, before any
191 /// job runs, to check that a pipeline's seams line up.
192 #[no_mangle]
193 pub extern "C" fn cf_signature() -> usize {
194 $crate::__write_json(&<$ty as $crate::Block>::signature())
195 }
196
197 #[no_mangle]
198 pub extern "C" fn cf_init(ptr: usize, len: usize) -> usize {
199 let input: ::serde_json::Value = unsafe { $crate::__read_json(ptr, len) };
200 let cmd = __CF_STATE.with(|s| $crate::Block::start(&mut *s.borrow_mut(), input));
201 $crate::__write_json(&cmd)
202 }
203
204 #[no_mangle]
205 pub extern "C" fn cf_step(ptr: usize, len: usize) -> usize {
206 let event: $crate::Event = unsafe { $crate::__read_json(ptr, len) };
207 let cmd = __CF_STATE.with(|s| $crate::Block::step(&mut *s.borrow_mut(), event));
208 $crate::__write_json(&cmd)
209 }
210
211 #[no_mangle]
212 pub extern "C" fn cf_on_token(ptr: usize, len: usize) -> i32 {
213 // Lossy on purpose: a model can emit a token split mid-character,
214 // and mangling one character is a far better outcome than trapping
215 // the whole job over it.
216 let token: ::std::string::String = unsafe {
217 let slice = ::std::slice::from_raw_parts(ptr as *const u8, len);
218 ::std::string::String::from_utf8_lossy(slice).into_owned()
219 };
220 $crate::TokenAction::as_i32(
221 __CF_STATE.with(|s| $crate::Block::on_token(&mut *s.borrow_mut(), &token)),
222 )
223 }
224 };
225}