Skip to main content

simpleplatform_sdk/
lib.rs

1//! Write Simple platform actions in Rust.
2//!
3//! ```no_run
4//! use simpleplatform_sdk::prelude::*;
5//!
6//! #[derive(Deserialize)]
7//! struct Input {
8//!     customer_id: String,
9//! }
10//!
11//! #[derive(Deserialize)]
12//! struct Open {
13//!     invoices: Vec<Invoice>,
14//! }
15//!
16//! #[derive(Deserialize)]
17//! struct Invoice {
18//!     amount: f64,
19//! }
20//!
21//! #[derive(Serialize)]
22//! struct Output {
23//!     customer_id: String,
24//!     total: f64,
25//! }
26//!
27//! const OPEN_INVOICES: &str = r#"
28//!   query Open($id: ID!) {
29//!     invoices: crm__invoice(where: {customer_id: {_eq: $id}, status: {_eq: "open"}}, limit: 500) {
30//!       amount
31//!     }
32//!   }"#;
33//!
34//! fn main() {
35//!     simple::run(|request: Request<Input>| {
36//!         let open: Open =
37//!             simple::graphql::query(OPEN_INVOICES, json!({ "id": request.data.customer_id }))?;
38//!
39//!         Ok(Output {
40//!             total: open.invoices.iter().map(|invoice| invoice.amount).sum(),
41//!             customer_id: request.data.customer_id,
42//!         })
43//!     })
44//! }
45//! ```
46//!
47//! No lifetimes, no `async`, no `unsafe`, no envelope, no context threading, one
48//! import line.
49//!
50//! # Describing an action
51//!
52//! What an action is, and what its input looks like, is written where the code
53//! is — in the doc comments and on the members themselves. There is nothing to
54//! keep in step by hand.
55//!
56//! Three tags describe the action, written with `///` in the doc comment above
57//! the handler — the same comment that carries its description:
58//!
59//! ```text
60//! /// Close a duplicate lead and point it at the record that survives.
61//! ///
62//! /// The surviving lead keeps its activity; the duplicate is marked closed
63//! /// and linked to it, so a later report still reaches both.
64//! ///
65//! /// @tool
66//! /// @shortdesc Close a duplicate lead, pointing it at the surviving record.
67//! /// @usewhen A lead is a duplicate of one already in the system.
68//! /// @usewhen Two leads share a contact and one should be retired.
69//! fn handler(request: Request<Input>) -> Result<Output, Error> { /* ... */ }
70//! ```
71//!
72//! - `@tool` — bare, with no value. It marks the action as one that can be
73//!   reached as a tool.
74//! - `@shortdesc` — one line, up to 300 characters. What this is, read in a
75//!   listing of tools.
76//! - `@usewhen` — one line, up to 100 characters, written up to ten times. One
77//!   occasion each, for reaching for this rather than something else.
78//!
79//! The prose above the tags stays as written, and is the full description.
80//!
81//! [`Schema`] describes the members, and [the derive's own
82//! documentation](Schema) is the reference for it:
83//!
84//! ```
85//! use simpleplatform_sdk::prelude::*;
86//!
87//! /// The leads to consider.
88//! #[derive(Deserialize, Schema)]
89//! struct Input {
90//!     /// The leads to close, by identifier.
91//!     #[simple(length(min = 1, max = 500))]
92//!     ids: Vec<String>,
93//!
94//!     /// How far back to look for activity.
95//!     #[simple(range(min = 1, max = 90))]
96//!     days: u32,
97//!
98//!     /// Consider only leads whose reference starts here.
99//!     #[simple(pattern = "^KNOW", length(max = 64))]
100//!     prefix: Option<String>,
101//! }
102//! ```
103//!
104//! `#[derive(Schema)]` generates nothing at all. It makes `#[simple(…)]` legal
105//! to write and checks what is written in it, so a bound in the wrong shape is
106//! a compile error at the span that holds it rather than a surprise later.
107//!
108//! Three things are deliberately absent from `#[simple(…)]`, because each has
109//! one place already:
110//!
111//! - **The description** is the doc comment on the member.
112//! - **Requiredness** is the type: optional when `Option<T>` or
113//!   `#[serde(default)]`, required otherwise.
114//! - **The property name** is `serde`'s: `#[serde(rename = "…")]` and
115//!   `#[serde(rename_all = "…")]`.
116//!
117//! # What this crate takes on so an action does not
118//!
119//! Rust is a hard language and an action is a small piece of business logic.
120//! Resolving that tension is this crate's job:
121//!
122//! | Rust difficulty | who deals with it |
123//! |---|---|
124//! | lifetimes and borrows | nothing in the public surface carries one |
125//! | `async`, executors, `Pin` | a handler is a plain `fn`; asyncify is a build flag |
126//! | `unsafe`, raw pointers, the ABI | `abi.rs`, behind [`host::Transport`] |
127//! | `allocate_buffer`, memory | [`run`] owns it |
128//! | a panic inside a guest | the panic hook reports a failure envelope |
129//! | `Box<dyn Error>` conversion noise | `?` converts anything into [`Error`] |
130//! | choosing an error crate | there is one [`Error`], and it ships here |
131//! | forgetting to report a result | [`run`] guarantees exactly one `__done__` |
132//! | naming a failure the platform can file | [`Code`] is the vocabulary |
133//! | writing a mock host in every action | [`testing`] |
134//!
135//! # The parts
136//!
137//! - [`run`] — the entry point, and the one report it makes.
138//! - [`Request`] — a payload already parsed into your own input type.
139//! - [`Error`] and [`Code`] — one error type, one failure vocabulary.
140//! - [`Schema`] — the constraints on a member, checked as you write them.
141//! - [`testing`] — a host on your own machine, with no wasm anywhere.
142//!
143//! Five modules reach the platform, and each answers with the type the call site
144//! asked for:
145//!
146//! - [`graphql`] — reading and writing tenant data.
147//! - [`http`] — calling a service outside the platform.
148//! - [`ai`] — extracting, summarising, transcribing, and the face collection.
149//! - [`settings`] — the settings an application was configured with.
150//! - [`storage`] — putting a file into the platform's store, and the
151//!   [`DocumentHandle`] that comes back.
152//!
153//! They compose in one handler: read the configuration with [`settings`], store
154//! a file with [`storage`], read what it says with [`ai`], and write the record
155//! with [`graphql`] — one `?` between each, and one [`Error`] out of all of them.
156//! `examples/file_expense_receipt.rs` is that action, written out.
157//!
158//! # Building an action
159//!
160//! Two artifacts from one source. The default build is for the server, which
161//! answers a host call synchronously:
162//!
163//! ```text
164//! cargo build --target wasm32-wasip1 --release
165//! ```
166//!
167//! The `async` build is for the browser, where a host call parks the module and
168//! `wasm-opt --asyncify` resumes it:
169//!
170//! ```text
171//! cargo build --target wasm32-wasip1 --release --features async
172//! wasm-opt release.ori.async.wasm -Oz --disable-gc \
173//!   --enable-bulk-memory --enable-bulk-memory-opt --enable-sign-ext \
174//!   --enable-nontrapping-float-to-int --enable-multivalue --enable-reference-types \
175//!   --asyncify --pass-arg=asyncify-imports@simple.__call -o release.async.wasm
176//! ```
177//!
178//! The `--enable-*` flags are required: Rust's `wasm32-wasip1` target enables
179//! bulk memory and friends by default, and binaryen validates the features it is
180//! told about.
181//!
182//! The two builds declare different imports, which is what the `async` feature
183//! selects for you. See `src/abi.rs`.
184
185#![deny(missing_docs)]
186#![deny(unsafe_code)]
187#![deny(rustdoc::broken_intra_doc_links)]
188
189#[allow(unsafe_code)]
190#[cfg(target_arch = "wasm32")]
191mod abi;
192
193pub mod ai;
194pub mod codes;
195mod envelope;
196mod error;
197pub mod graphql;
198pub mod host;
199pub mod http;
200mod run;
201pub mod settings;
202pub mod storage;
203
204#[cfg(not(target_arch = "wasm32"))]
205pub mod testing;
206
207pub use crate::codes::{Category, Code};
208pub use crate::error::{Error, Fault};
209pub use crate::host::Transport;
210pub use crate::run::{run, Context, Headers, Logic, Request, Tenant, User};
211
212/// A stored file, re-exported from [`storage`].
213///
214/// It is here because it belongs to more than one module: [`storage`] answers
215/// with it, [`ai`] reads one, [`graphql`] writes one into a `:document` field,
216/// and an action names it in its own output type. The definition and its
217/// documentation live in [`storage`].
218pub use crate::storage::DocumentHandle;
219
220/// Constraints on the members of an action's types, re-exported.
221///
222/// The derive lives in its own crate, because a crate that defines a procedural
223/// macro may export only macros. An action never names that crate: it depends
224/// on this one, whose default `derive` feature brings the derive in and puts it
225/// here and in the [`prelude`], so `use simpleplatform_sdk::prelude::*;` is
226/// still the whole import list. The `simple` helper attribute comes with it.
227///
228/// An action that writes no constraints turns the feature off with
229/// `default-features = false`, and then compiles no procedural macro at all.
230#[cfg(feature = "derive")]
231pub use simpleplatform_sdk_macros::Schema;
232
233/// `serde`, re-exported.
234///
235/// An action normally depends on `serde` itself — the generated `Cargo.toml`
236/// lists it — because a `#[derive(Deserialize)]` expands to code that names the
237/// crate. This re-export is here for an action that would rather not, and can
238/// write `#[serde(crate = "simpleplatform_sdk::serde")]` instead.
239pub use serde;
240
241/// `serde_json`, re-exported, for the same reason as [`serde`].
242pub use serde_json;
243
244/// Everything an action needs, in one line.
245///
246/// ```
247/// use simpleplatform_sdk::prelude::*;
248/// ```
249///
250/// That brings in [`simple`](crate) itself — so a call reads `simple::run`,
251/// `simple::graphql::query` and `simple::http::get` — along with [`Request`],
252/// [`Error`], [`Value`](serde_json::Value), the [`json!`](serde_json::json)
253/// macro, the two serde derives, and [`Schema`], which carries the
254/// `#[simple(…)]` attribute with it.
255///
256/// # What a module puts here, and what it keeps
257///
258/// A module's types stay in the module. The exception is a type an action has
259/// to write down in order to make the call — the ones that appear in a public
260/// signature, which are the options a call takes and the value it answers with:
261/// [`ai::Options`], [`ai::TranscribeOptions`], [`ai::FaceSearch`],
262/// [`ai::Execution`], [`storage::Source`], [`storage::Target`] and
263/// [`DocumentHandle`].
264///
265/// What a call chooses *inside* one of those is reached through its own module
266/// and needs no import, because [`simple`](crate) is already in scope:
267/// `simple::ai::Model::Large`, `simple::ai::Participants::Detect`,
268/// `simple::storage::Auth::bearer("t-1234")`. A settings read names no type at
269/// all, and neither do the five HTTP method functions.
270///
271/// [`http::Request`] is the one signature type that stays in its module, so that
272/// `Request` here always means the request an action was called with. An
273/// outbound request is written under the module it belongs to —
274/// `use simpleplatform_sdk::http;`, then `http::fetch(http::Request { .. })` —
275/// which keeps both names available in the same file, each meaning one thing.
276pub mod prelude {
277    pub use crate as simple;
278
279    pub use crate::ai::{Execution, FaceSearch, Options, TranscribeOptions};
280    pub use crate::codes::{Category, Code};
281    pub use crate::error::Error;
282    pub use crate::run::{Context, Request};
283    pub use crate::storage::{DocumentHandle, Source, Target};
284
285    #[cfg(feature = "derive")]
286    pub use crate::Schema;
287
288    pub use serde::{Deserialize, Serialize};
289    pub use serde_json::{json, Value};
290}