Expand description
Write Simple platform actions in Rust.
use simpleplatform_sdk::prelude::*;
#[derive(Deserialize)]
struct Input {
customer_id: String,
}
#[derive(Deserialize)]
struct Open {
invoices: Vec<Invoice>,
}
#[derive(Deserialize)]
struct Invoice {
amount: f64,
}
#[derive(Serialize)]
struct Output {
customer_id: String,
total: f64,
}
const OPEN_INVOICES: &str = r#"
query Open($id: ID!) {
invoices: crm__invoice(where: {customer_id: {_eq: $id}, status: {_eq: "open"}}, limit: 500) {
amount
}
}"#;
fn main() {
simple::run(|request: Request<Input>| {
let open: Open =
simple::graphql::query(OPEN_INVOICES, json!({ "id": request.data.customer_id }))?;
Ok(Output {
total: open.invoices.iter().map(|invoice| invoice.amount).sum(),
customer_id: request.data.customer_id,
})
})
}No lifetimes, no async, no unsafe, no envelope, no context threading, one
import line.
§Describing an action
What an action is, and what its input looks like, is written where the code is — in the doc comments and on the members themselves. There is nothing to keep in step by hand.
Three tags describe the action, written with /// in the doc comment above
the handler — the same comment that carries its description:
/// Close a duplicate lead and point it at the record that survives.
///
/// The surviving lead keeps its activity; the duplicate is marked closed
/// and linked to it, so a later report still reaches both.
///
/// @tool
/// @shortdesc Close a duplicate lead, pointing it at the surviving record.
/// @usewhen A lead is a duplicate of one already in the system.
/// @usewhen Two leads share a contact and one should be retired.
fn handler(request: Request<Input>) -> Result<Output, Error> { /* ... */ }@tool— bare, with no value. It marks the action as one that can be reached as a tool.@shortdesc— one line, up to 300 characters. What this is, read in a listing of tools.@usewhen— one line, up to 100 characters, written up to ten times. One occasion each, for reaching for this rather than something else.
The prose above the tags stays as written, and is the full description.
Schema describes the members, and the derive’s own
documentation is the reference for it:
use simpleplatform_sdk::prelude::*;
/// The leads to consider.
#[derive(Deserialize, Schema)]
struct Input {
/// The leads to close, by identifier.
#[simple(length(min = 1, max = 500))]
ids: Vec<String>,
/// How far back to look for activity.
#[simple(range(min = 1, max = 90))]
days: u32,
/// Consider only leads whose reference starts here.
#[simple(pattern = "^KNOW", length(max = 64))]
prefix: Option<String>,
}#[derive(Schema)] generates nothing at all. It makes #[simple(…)] legal
to write and checks what is written in it, so a bound in the wrong shape is
a compile error at the span that holds it rather than a surprise later.
Three things are deliberately absent from #[simple(…)], because each has
one place already:
- The description is the doc comment on the member.
- Requiredness is the type: optional when
Option<T>or#[serde(default)], required otherwise. - The property name is
serde’s:#[serde(rename = "…")]and#[serde(rename_all = "…")].
§What this crate takes on so an action does not
Rust is a hard language and an action is a small piece of business logic. Resolving that tension is this crate’s job:
| Rust difficulty | who deals with it |
|---|---|
| lifetimes and borrows | nothing in the public surface carries one |
async, executors, Pin | a handler is a plain fn; asyncify is a build flag |
unsafe, raw pointers, the ABI | abi.rs, behind host::Transport |
allocate_buffer, memory | run owns it |
| a panic inside a guest | the panic hook reports a failure envelope |
Box<dyn Error> conversion noise | ? converts anything into Error |
| choosing an error crate | there is one Error, and it ships here |
| forgetting to report a result | run guarantees exactly one __done__ |
| naming a failure the platform can file | Code is the vocabulary |
| writing a mock host in every action | testing |
§The parts
run— the entry point, and the one report it makes.Request— a payload already parsed into your own input type.ErrorandCode— one error type, one failure vocabulary.Schema— the constraints on a member, checked as you write them.testing— a host on your own machine, with no wasm anywhere.
Five modules reach the platform, and each answers with the type the call site asked for:
graphql— reading and writing tenant data.http— calling a service outside the platform.ai— extracting, summarising, transcribing, and the face collection.settings— the settings an application was configured with.storage— putting a file into the platform’s store, and theDocumentHandlethat comes back.
They compose in one handler: read the configuration with settings, store
a file with storage, read what it says with ai, and write the record
with graphql — one ? between each, and one Error out of all of them.
examples/file_expense_receipt.rs is that action, written out.
§Building an action
Two artifacts from one source. The default build is for the server, which answers a host call synchronously:
cargo build --target wasm32-wasip1 --releaseThe async build is for the browser, where a host call parks the module and
wasm-opt --asyncify resumes it:
cargo build --target wasm32-wasip1 --release --features async
wasm-opt release.ori.async.wasm -Oz --disable-gc \
--enable-bulk-memory --enable-bulk-memory-opt --enable-sign-ext \
--enable-nontrapping-float-to-int --enable-multivalue --enable-reference-types \
--asyncify --pass-arg=asyncify-imports@simple.__call -o release.async.wasmThe --enable-* flags are required: Rust’s wasm32-wasip1 target enables
bulk memory and friends by default, and binaryen validates the features it is
told about.
The two builds declare different imports, which is what the async feature
selects for you. See src/abi.rs.
Re-exports§
pub use crate::codes::Category;pub use crate::codes::Code;pub use crate::host::Transport;pub use crate::storage::DocumentHandle;pub use serde;pub use serde_json;
Modules§
- ai
- Asking the AI engine for an answer.
- codes
- The failure vocabulary an action may report, as a closed enum.
- graphql
- Reading and writing tenant data.
- host
- The ambient transport: what an action talks to, and where it is kept.
- http
- Calling a service outside the platform.
- prelude
- Everything an action needs, in one line.
- settings
- Reading the settings an application was configured with.
- storage
- Putting a file into the platform’s store, and reading one back out.
- testing
- Running an action on your own machine, with no host and no wasm.
Structs§
- Context
- The execution context, as the host assembled it.
- Fault
- Everything a failure carries onto the wire.
- Logic
- Which logic execution this is.
- Request
- One incoming request, with its payload already parsed.
- Tenant
- Which tenant this is running for.
- User
- Who this is running for, when it is running for anybody.
Enums§
- Error
- Everything that can go wrong inside an action.
Functions§
- run
- Run an action.
Type Aliases§
- Headers
- Request headers, as the host assembled them.
Derive Macros§
- Schema
- Constraints on the members of an action’s types, re-exported.