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//! Four 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//! - `@parallelsafe` — bare, with no value, written only alongside `@tool`; the
79//! build refuses it without `@tool`, with a value, or written twice. It
80//! claims that the action changes no stored data and sends nothing, so it may
81//! run at the same time as the other parallel-safe calls next to it in a
82//! batch; every other call still runs alone, in the order asked. The platform
83//! does not verify the claim, and it changes dispatch only — never whether a
84//! failed call is retried, nor the assumption that a failed call may have
85//! changed stored data.
86//!
87//! The prose above the tags stays as written, and is the full description.
88//!
89//! [`Schema`] describes the members, and [the derive's own
90//! documentation](Schema) is the reference for it:
91//!
92//! ```
93//! use simpleplatform_sdk::prelude::*;
94//!
95//! /// The leads to consider.
96//! #[derive(Deserialize, Schema)]
97//! struct Input {
98//! /// The leads to close, by identifier.
99//! #[simple(length(min = 1, max = 500))]
100//! ids: Vec<String>,
101//!
102//! /// How far back to look for activity.
103//! #[simple(range(min = 1, max = 90))]
104//! days: u32,
105//!
106//! /// Consider only leads whose reference starts here.
107//! #[simple(pattern = "^KNOW", length(max = 64))]
108//! prefix: Option<String>,
109//! }
110//! ```
111//!
112//! `#[derive(Schema)]` generates nothing at all. It makes `#[simple(…)]` legal
113//! to write and checks what is written in it, so a bound in the wrong shape is
114//! a compile error at the span that holds it rather than a surprise later.
115//!
116//! Three things are deliberately absent from `#[simple(…)]`, because each has
117//! one place already:
118//!
119//! - **The description** is the doc comment on the member.
120//! - **Requiredness** is the type: optional when `Option<T>` or
121//! `#[serde(default)]`, required otherwise.
122//! - **The property name** is `serde`'s: `#[serde(rename = "…")]` and
123//! `#[serde(rename_all = "…")]`.
124//!
125//! # What this crate takes on so an action does not
126//!
127//! Rust is a hard language and an action is a small piece of business logic.
128//! Resolving that tension is this crate's job:
129//!
130//! | Rust difficulty | who deals with it |
131//! |---|---|
132//! | lifetimes and borrows | nothing in the public surface carries one |
133//! | `async`, executors, `Pin` | a handler is a plain `fn`; asyncify is a build flag |
134//! | `unsafe`, raw pointers, the ABI | `abi.rs`, behind [`host::Transport`] |
135//! | `allocate_buffer`, memory | [`run`] owns it |
136//! | a panic inside a guest | the panic hook reports a failure envelope |
137//! | `Box<dyn Error>` conversion noise | `?` converts anything into [`Error`] |
138//! | choosing an error crate | there is one [`Error`], and it ships here |
139//! | forgetting to report a result | [`run`] guarantees exactly one `__done__` |
140//! | naming a failure the platform can file | [`Code`] is the vocabulary |
141//! | writing a mock host in every action | [`testing`] |
142//!
143//! # The parts
144//!
145//! - [`run`] — the entry point, and the one report it makes.
146//! - [`Request`] — a payload already parsed into your own input type.
147//! - [`Error`] and [`Code`] — one error type, one failure vocabulary.
148//! - [`Schema`] — the constraints on a member, checked as you write them.
149//! - [`testing`] — a host on your own machine, with no wasm anywhere.
150//!
151//! Five modules reach the platform, and each answers with the type the call site
152//! asked for:
153//!
154//! - [`graphql`] — reading and writing tenant data.
155//! - [`http`] — calling a service outside the platform.
156//! - [`ai`] — extracting, summarising, transcribing, and the face collection.
157//! - [`settings`] — the settings an application was configured with.
158//! - [`storage`] — putting a file into the platform's store, and the
159//! [`DocumentHandle`] that comes back.
160//!
161//! They compose in one handler: read the configuration with [`settings`], store
162//! a file with [`storage`], read what it says with [`ai`], and write the record
163//! with [`graphql`] — one `?` between each, and one [`Error`] out of all of them.
164//! `examples/file_expense_receipt.rs` is that action, written out.
165//!
166//! # Building an action
167//!
168//! Two artifacts from one source. The default build is for the server, which
169//! answers a host call synchronously:
170//!
171//! ```text
172//! cargo build --target wasm32-wasip1 --release
173//! ```
174//!
175//! The `async` build is for the browser, where a host call parks the module and
176//! `wasm-opt --asyncify` resumes it:
177//!
178//! ```text
179//! cargo build --target wasm32-wasip1 --release --features async
180//! wasm-opt release.ori.async.wasm -Oz --disable-gc \
181//! --enable-bulk-memory --enable-bulk-memory-opt --enable-sign-ext \
182//! --enable-nontrapping-float-to-int --enable-multivalue --enable-reference-types \
183//! --asyncify --pass-arg=asyncify-imports@simple.__call -o release.async.wasm
184//! ```
185//!
186//! The `--enable-*` flags are required: Rust's `wasm32-wasip1` target enables
187//! bulk memory and friends by default, and binaryen validates the features it is
188//! told about.
189//!
190//! The two builds declare different imports, which is what the `async` feature
191//! selects for you. See `src/abi.rs`.
192
193#![deny(missing_docs)]
194#![deny(unsafe_code)]
195#![deny(rustdoc::broken_intra_doc_links)]
196
197#[allow(unsafe_code)]
198#[cfg(target_arch = "wasm32")]
199mod abi;
200
201pub mod ai;
202pub mod codes;
203mod envelope;
204mod error;
205pub mod graphql;
206pub mod host;
207pub mod http;
208mod run;
209pub mod settings;
210pub mod storage;
211pub mod tasks;
212
213#[cfg(not(target_arch = "wasm32"))]
214pub mod testing;
215
216pub use crate::codes::{Category, Code};
217pub use crate::error::{Error, Fault};
218pub use crate::host::Transport;
219pub use crate::run::{run, Context, Headers, Logic, Request, Tenant, User};
220
221/// A stored file, re-exported from [`storage`].
222///
223/// It is here because it belongs to more than one module: [`storage`] answers
224/// with it, [`ai`] reads one, [`graphql`] writes one into a `:document` field,
225/// and an action names it in its own output type. The definition and its
226/// documentation live in [`storage`].
227pub use crate::storage::DocumentHandle;
228
229/// Constraints on the members of an action's types, re-exported.
230///
231/// The derive lives in its own crate, because a crate that defines a procedural
232/// macro may export only macros. An action never names that crate: it depends
233/// on this one, whose default `derive` feature brings the derive in and puts it
234/// here and in the [`prelude`], so `use simpleplatform_sdk::prelude::*;` is
235/// still the whole import list. The `simple` helper attribute comes with it.
236///
237/// An action that writes no constraints turns the feature off with
238/// `default-features = false`, and then compiles no procedural macro at all.
239#[cfg(feature = "derive")]
240pub use simpleplatform_sdk_macros::Schema;
241
242/// `serde`, re-exported.
243///
244/// An action normally depends on `serde` itself — the generated `Cargo.toml`
245/// lists it — because a `#[derive(Deserialize)]` expands to code that names the
246/// crate. This re-export is here for an action that would rather not, and can
247/// write `#[serde(crate = "simpleplatform_sdk::serde")]` instead.
248pub use serde;
249
250/// `serde_json`, re-exported, for the same reason as [`serde`].
251pub use serde_json;
252
253/// Everything an action needs, in one line.
254///
255/// ```
256/// use simpleplatform_sdk::prelude::*;
257/// ```
258///
259/// That brings in [`simple`](crate) itself — so a call reads `simple::run`,
260/// `simple::graphql::query` and `simple::http::get` — along with [`Request`],
261/// [`Error`], [`Value`](serde_json::Value), the [`json!`](serde_json::json)
262/// macro, the two serde derives, and [`Schema`], which carries the
263/// `#[simple(…)]` attribute with it.
264///
265/// # What a module puts here, and what it keeps
266///
267/// A module's types stay in the module. The exception is a type an action has
268/// to write down in order to make the call — the ones that appear in a public
269/// signature, which are the options a call takes and the value it answers with:
270/// [`ai::Options`], [`ai::TranscribeOptions`], [`ai::FaceSearch`],
271/// [`ai::Execution`], [`storage::Source`], [`storage::Target`] and
272/// [`DocumentHandle`].
273///
274/// What a call chooses *inside* one of those is reached through its own module
275/// and needs no import, because [`simple`](crate) is already in scope:
276/// `simple::ai::Model::Large`, `simple::ai::Participants::Detect`,
277/// `simple::storage::Auth::bearer("t-1234")`. A settings read names no type at
278/// all, and neither do the five HTTP method functions.
279///
280/// [`http::Request`] is the one signature type that stays in its module, so that
281/// `Request` here always means the request an action was called with. An
282/// outbound request is written under the module it belongs to —
283/// `use simpleplatform_sdk::http;`, then `http::fetch(http::Request { .. })` —
284/// which keeps both names available in the same file, each meaning one thing.
285pub mod prelude {
286 pub use crate as simple;
287
288 pub use crate::ai::{Execution, FaceSearch, Options, TranscribeOptions};
289 pub use crate::codes::{Category, Code};
290 pub use crate::error::Error;
291 pub use crate::run::{Context, Request};
292 pub use crate::storage::{DocumentHandle, Source, Target};
293
294 #[cfg(feature = "derive")]
295 pub use crate::Schema;
296
297 pub use serde::{Deserialize, Serialize};
298 pub use serde_json::{json, Value};
299}