Skip to content

Rust

The Rust function SDK is the smallest way to ship a function: the crate flowcatalyst-fn compiles to wasm32-unknown-unknown (no WASI), and the hello example is about 137 KB (120 KB after wasm-opt -Os --enable-bulk-memory). Its only dependencies are serde and serde_json (with preserve_order, so database rows keep the column order).

The same contract is implemented by the Go, TypeScript and Java SDKs. Functions are first-party code (decision).

The crate is not yet released: its VERSION is 0.0.0 and no fn-rust-sdk tag exists. The release process splits clients/fn-rust into a standalone repository, flowcatalyst/fn-rust-sdk, tagged vX.Y.Z, and a crates.io publish is planned but off. Until a tag exists, depend on a checkout of the platform repository:

[lib]
crate-type = ["cdylib"]
[dependencies]
flowcatalyst-fn = { path = "../path-to/clients/fn-rust" }
serde_json = { version = "1", features = ["preserve_order"] }
[profile.release]
opt-level = "s"
lto = true
panic = "abort"
strip = true

Once the split repository is tagged, use flowcatalyst-fn = { git = "https://github.com/flowcatalyst/fn-rust-sdk", tag = "vX.Y.Z" }. fcdev fn init writes a Rust project (a --sdk-path flag points it at a local checkout of the SDKs); its default template names a crates.io version that does not exist yet, so use --sdk-path for now.

flowcatalyst_fn::export! takes a registration closure (or a fn(&mut App)) and expands to the four Guest ABI v1 exports. The App is rebuilt for each call, so registration is only pattern strings and fn pointers.

use flowcatalyst_fn::{App, Context, Error, Request, Response};
flowcatalyst_fn::export!(|app: &mut App| {
app.open("GET /healthz", health)
.platform("GET /hello/{name}", hello)
.webhook("POST /events/x", on_event)
.subscribe("t:y:z:w", "/events/x")
.schedule("0 */5 * * * *", "/events/x")
.config("GREETING")
.secret("API_KEY")
.db("main")
.http_allow("api.example.com")
.emits("a:b:c:d");
});
fn hello(req: &Request, ctx: &Context) -> Result<Response, Error> {
let g = ctx.config_get("GREETING")?.unwrap_or_else(|| "Hello".into());
let who = req.path_param("name").unwrap_or("");
Ok(Response::new(200).with_body(format!("{g}, {who}").into_bytes()))
}

Handlers are plain fn(&Request, &Context) -> Result<Response, Error> pointers, not closures. An Err becomes a 500 with a fixed body, and the error is logged. There is no panic recovery: with panic = "abort" a panic traps the instance, which the runner reports as 500 FUNCTION_FAILED.

Terminal window
cargo build --release --target wasm32-unknown-unknown

The artifact is the cdylib .wasm under target/wasm32-unknown-unknown/release/.

Method Declares
webhook(pattern, handler) A webhook endpoint (signature-verified delivery)
platform(pattern, handler) An endpoint needing a verified platform token
open(pattern, handler) An endpoint with no authentication
subscribe(event_type, path) Deliveries of an event type go to the webhook at path
schedule(cron, path) A six-field cron firing (seconds first) at the webhook at path
config(key), secret(key), db(name) Config key, secret key, database binding
http_allow(host) A host outbound HTTP may reach
emits(event_type) An event type the function may emit
dispatches_with(target, path, DispatchOpts::new("conn-code").pool("pool-code")) A dispatch target; the connection is required, the pool optional
platform_token() Permission to fetch a platform access token
trace_context(name, description) A named trace context

The Rust builder does not yet offer the per-endpoint options (timeout, body cap, CORS) or subscription and schedule modifiers (mode, retries, data-only, timezone, payload) that the Go and TypeScript SDKs have; the describe entries omit those fields. This is a known gap, and the stability contract says a capability lands in all SDKs before it is documented as public.

Request has header(name), path_param(name), query() (the raw query string) and body(). Context gives caller() and invocation(). Caller has kind() and principal(), and Principal has is_anchor, has_role, can_access_client, can_access_client_code, can_access_application, can_access_application_code and has_permission (wildcard matching, as in the platform).

Response::new(status) with .with_header(name, value) and .with_body(bytes), or Response::json(status, &value)?. Delivery outcomes are ordinary responses: a 2xx is delivered; Response::new(429).with_header("Retry-After", "5") defers without spending an attempt; and Response::new(422).with_header("FlowCatalyst-Outcome", "reject") gives up (delivery).

Method Does
config_get(key), secret_get(key) Result<Option<String>, CapabilityError>
http_fetch(HttpRequest) Outbound call to an allowed host. Set timeout_ms yourself; 0 means the host default, because a wasm32-unknown-unknown guest has no clock
emit(Event) Publish a declared event; returns the event id. Event has event_type, source, subject, dedup_id, correlation_id, causation_id, message_group, content_type, data
dispatch(Job) Create a dispatch job; returns the job id. Not de-duplicated. Job has target, path, payload, code, subject, metadata (a BTreeMap), message_group, mode, correlation_id, causation_id, content_type, descriptor, max_retries, timeout_seconds, data_only
platform_token(), refresh_platform_token() The linked service account’s access token; refresh skips the cache
db_query(db, sql, params, tx), db_exec(...) Rows (Vec<Row>, an order-preserving map) or rows affected; tx is Option<&str>
db_begin(db), db_commit(tx), db_rollback(tx) Explicit transactions
log(level, msg, attrs), log_info, log_warn, log_error Logging
trace(context, msg, data, TraceOpts), tracing(context), set_reference(ref) Trace logs; TraceOpts::new().level(TraceLevel::Warn).reference(ref)
use flowcatalyst_fn::Event;
let id = ctx.emit(Event {
event_type: "a:b:c:d".into(),
dedup_id: format!("sent-{}", inbound_id),
content_type: "application/json".into(),
data: br#"{"ok":true}"#.to_vec(),
..Default::default()
})?;

Capability calls return CapabilityError. is_retryable() is true only for platform trouble (UNAVAILABLE), and code() gives the host’s code (NOT_DECLARED, NOT_ALLOWED, DEADLINE, TOO_LARGE, BAD_REQUEST, DB_*). It converts into the handler Error with ?. Retry only the retryable ones and reject the rest. Trace calls never fail; an older runner’s UNKNOWN_OP is swallowed.

The testing module runs a request through the real path (frame, route, handler, frame) on the host target. Define registration as a function so the test and export! share it:

fn register(app: &mut App) { app.open("GET /healthz", health); }
flowcatalyst_fn::export!(register);
#[test]
fn healthz() {
use flowcatalyst_fn::testing::{self, TestRequest};
let r = testing::invoke(register, TestRequest::new("GET", "/healthz"));
assert_eq!(r.status, 200);
}

TestRequest::new(method, path) takes .query(), .header(), .body(), .principal(id, permissions) and .webhook(); the default caller is anonymous. testing::describe(register) returns the describe JSON, and testing::host_ok / host_error build scripted results for set_fake_host, with fake_host_calls() recording the calls. Run with cargo test --manifest-path clients/fn-rust/Cargo.toml (65 tests in the SDK itself).

For the real runner without a platform, use fcdev fn dev (Develop locally).

Per-function defaults: 64 MB memory, 16 concurrent calls, 30 s timeout, 1 MiB request body. See Functions and the describe reference.