Write a function
This guide takes you from an empty directory to a function that has a health check, a platform-authenticated endpoint and a webhook endpoint that reacts to an event. Read Functions first if you want the model (addresses, versions, aliases and the trust model); this page is the practical part.
A function is first-party code: you write it as an operator of the platform, for your own customers’ benefit. The sandbox it runs in isolates faults, not hostile authors.
Choose a language
Section titled “Choose a language”| Language | Artifact | Runs on | Pick it when |
|---|---|---|---|
| TypeScript | one bundled script | the runner’s shared JavaScript engine | the logic is mapping and glue, and your team already writes TypeScript |
| Go | a WebAssembly module (GOOS=wasip1) |
the runner’s WebAssembly engine | you want plain net/http handlers; expect a 7 to 8 MB artifact |
| Rust | a WebAssembly module (wasm32-unknown-unknown) |
the runner’s WebAssembly engine | latency or density matter: about 0.14 MB, tens of microseconds per call |
| Java 25 | a fat jar | the ingestor runtime, not the runner | the function needs JVM libraries; one instance serves every call, so it must be thread-safe |
All four declare the same things and answer the same way. A function is a JVM function or not from
its first version: publishing a jar for a function that has Wasm or JavaScript versions (or the
reverse) is refused with RUNTIME_MISMATCH. Go cannot use TinyGo today (its http.ServeMux does not
match method patterns), and fcdev fn build always uses the standard Go toolchain.
Scaffold a project
Section titled “Scaffold a project”fcdev fn init --lang go --app billing invoice-pdf # or --lang rust / --lang tscd invoice-pdfgo mod tidy # npm install for ts--app is the owning application’s code; the function’s address will be billing.invoice-pdf
(lower-case letters, digits and hyphens in the name). fcdev fn init writes Go, Rust and TypeScript
projects; there is no scaffold for Java, which is an ordinary Maven project (below).
Handlers and the three kinds of endpoint
Section titled “Handlers and the three kinds of endpoint”Every endpoint names exactly one auth mode, and there is no default:
| Declared with | Who calls it | What the runner checks before your code runs |
|---|---|---|
Webhook |
subscriptions, schedules and dispatch jobs | the platform’s delivery signature |
Platform |
people and services holding a platform token | a valid access token; your code then checks permissions and client access |
Open |
anyone | nothing; verify third-party signatures yourself |
A webhook endpoint accepts POST only. Paths follow Go’s routing patterns (/orders/{id},
/files/{rest...}) in every language.
import { fn } from "@flowcatalyst/fn";
const greeting = fn.config("GREETING");
fn.open("GET /healthz", () => fn.json(200, { status: "ok" }));
fn.platform("GET /hello/{name}", (req) => fn.json(200, { message: `${greeting.get() ?? "Hello"}, ${req.params.name}`, caller: req.caller.principal?.id, }),);
fn.webhook("POST /events/greeting", async (req) => { const ev = req.json() as { id?: string }; await fn.emit({ type: "hello:greeting:greeting:sent", dedupId: `greeting-sent-${ev.id}`, // derived from the delivered event data: { ok: true }, }); return fn.status(202);});
fn.emits("hello:greeting:greeting:sent");package main
import ( "encoding/json" "net/http" "time"
fn "github.com/flowcatalyst/flowcatalyst/clients/fn-go")
var greeting = fn.Config("GREETING")
func init() { fn.Open("GET /healthz", health) fn.Platform("GET /hello/{name}", hello) fn.Webhook("POST /events/greeting", onGreeting) fn.Emits("hello:greeting:greeting:sent")}
func main() {}
func health(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) }
func hello(w http.ResponseWriter, r *http.Request) { g, found, err := greeting.Get(r.Context()) if err != nil || !found { g = "Hello" } resp := map[string]any{"message": g + ", " + r.PathValue("name")} if p := fn.CallerFrom(r.Context()).Principal(); p != nil { resp["caller"] = p.ID } w.Header().Set("Content-Type", "application/json") _ = json.NewEncoder(w).Encode(resp)}
func onGreeting(w http.ResponseWriter, r *http.Request) { var in struct{ ID string `json:"id"` } _ = json.NewDecoder(r.Body).Decode(&in) if in.ID == "" { in.ID = fn.Invocation(r.Context()).ID } _, err := fn.Emit(r.Context(), fn.Event{ Type: "hello:greeting:greeting:sent", DedupID: "greeting-sent-" + in.ID, ContentType: "application/json", Data: []byte(`{"ok":true}`), }) if err != nil { fn.Retry(w, 5*time.Second) // platform trouble: try again, no attempt spent return } w.WriteHeader(http.StatusAccepted)}use flowcatalyst_fn::{App, Context, Error, Event, Request, Response};
flowcatalyst_fn::export!(|app: &mut App| { app.open("GET /healthz", health) .platform("GET /hello/{name}", hello) .webhook("POST /events/greeting", on_greeting) .config("GREETING") .emits("hello:greeting:greeting:sent");});
fn health(_req: &Request, _ctx: &Context) -> Result<Response, Error> { Ok(Response::new(200).with_body(br#"{"status":"ok"}"#.to_vec()))}
fn hello(req: &Request, ctx: &Context) -> Result<Response, Error> { let g = ctx.config_get("GREETING").ok().flatten().unwrap_or_else(|| "Hello".into()); let mut body = serde_json::json!({ "message": format!("{g}, {}", req.path_param("name").unwrap_or("")) }); if let Some(p) = ctx.caller().principal() { body["caller"] = serde_json::json!(p.id); } Response::json(200, &body)}
fn on_greeting(req: &Request, ctx: &Context) -> Result<Response, Error> { let inbound: serde_json::Value = serde_json::from_slice(&req.body).unwrap_or_default(); let id = inbound.get("id").and_then(|v| v.as_str()).unwrap_or(&req.id); match ctx.emit(Event { event_type: "hello:greeting:greeting:sent".into(), dedup_id: format!("greeting-sent-{id}"), content_type: "application/json".into(), data: br#"{"ok":true}"#.to_vec(), ..Default::default() }) { Ok(_) => Ok(Response::new(202)), Err(e) if e.is_retryable() => Ok(Response::new(429).with_header("Retry-After", "5")), Err(_) => Ok(Response::new(422) .with_header("FlowCatalyst-Outcome", "reject") .with_body(b"emit refused".to_vec())), }}public final class HelloFunction implements Function {
@Override public Result handle(Request in, FunctionContext ctx) throws Exception { return switch (in.route()) { // the pattern the describe declares case "GET /healthz" -> Result.json(200, "{\"status\":\"ok\"}"); case "GET /hello/{name}" -> hello(in, ctx); case "POST /events/greeting-requested" -> Result.ack(); default -> Result.fail("no handler for " + in.route()); }; }
private Result hello(Request in, FunctionContext ctx) { String greeting = ctx.config().get("GREETING").orElse("Hello"); return Result.json(200, "{\"message\":\"" + greeting + ", " + in.pathParams().get("name") + "\"}"); }}The class needs a public no-argument constructor and is declared in
src/main/resources/META-INF/flowcatalyst/function.json (see
Declare endpoints, auth, subscriptions and schedules). init(FunctionContext)
runs once before the first call and stop() once after the last. A Java function has no code-level
registration: the describe document is a file you write.
The complete, tested versions of the Go and Rust examples are clients/fn-go/examples/hello and
clients/fn-rust/examples/hello in the platform repository.
Who is calling
Section titled “Who is calling”A Platform endpoint receives a principal. Check what the caller may do in your own code: the
runner only proved the token valid.
- Go:
fn.CallerFrom(ctx).Principal()thenp.HasPermission("billing:invoice:view"),p.CanAccessClient(id),p.CanAccessClientCode("acme"). - TypeScript:
req.caller.principalwith the same methods in camel case. - Rust:
ctx.caller().principal(). - Java: the
Calleris aPrincipalwithhasPermission,canAccessClient,canAccessClientCode,canAccessApplicationandcanAccessApplicationCode.
Permission matching treats * as a segment wildcard, exactly as the platform does.
Answer deliveries
Section titled “Answer deliveries”A webhook endpoint is called by the messaging pipeline, so how you answer decides what happens next.
| Your answer | What the platform does |
|---|---|
| any 2xx | delivered |
429 with Retry-After (fn.Retry(w, d), fn.retry(5), Result.retry(d)) |
tries again after the delay, without spending an attempt |
422 with FlowCatalyst-Outcome: reject (fn.Reject(w, reason), fn.reject(reason), Result.reject(reason)) |
gives up at once: retrying cannot help |
| anything else, a crash or a timeout | a failed attempt, retried until the subscription’s or schedule’s limit |
Use the retry answer for platform trouble (an emit returned a retryable error), and reject for input
that will never be valid. A function that is past its concurrency limit answers 429 by itself, and
deliveries treat that as a deferral too. See Delivery for the platform side.
Emit events
Section titled “Emit events”A function may only emit event types it declared with Emits, and only types of its own
application. Every event needs a dedup id: derive it from what you are handling (the delivered
event’s id, or the invocation id as a fallback) so a redelivery emits once. A random dedup id would
turn every retry into a new event.
Everything else a function can reach
Section titled “Everything else a function can reach”Config and secrets, databases, outbound HTTP, dispatching work and calling other applications are all declared and bounded; each has its own guide:
- Give a function secrets and config
- Create a dispatch job from a function
- Call another service with a platform token
- Switch on trace logs and read them
Every call has a deadline (30 seconds by default), and it reaches databases, HTTP and emits too: when the time is up, everything the call started stops.
Test without a platform
Section titled “Test without a platform”Unit-test handlers on the host with the SDK’s fake host; no Wasm runtime or platform is needed.
- Go:
go test ./....fn.InvokeForTest(fn.TestRequest{...})runs a request through your router andfn.DescribeForTest()returns the describe document (neither compiles forwasip1). - Rust:
cargo test.testing::invoke,testing::describe,TestRequest,host_okandhost_errordo the same. Keep registration in a plainfn register(app: &mut App)shared withexport!(register). - TypeScript:
npm test(plainnode --testworks; the SDK falls back toTextEncoderwhen the engine’s natives are absent). - Java:
FakeFunctionContext,FakeRequest,RecordingEventsandRecordingDispatcherinio.flowcatalyst.function.testing.
Then run the real thing locally with fcdev fn dev.
Build and publish
Section titled “Build and publish”fcdev fn build # builds with your toolchain, then reads the describe as publishing willfcdev fn deploy billing.invoice-pdf . --create # publish, wait until loaded, promote liveA function that builds with fcdev fn build publishes. For Java, build a fat jar with Maven, marking
the function API (io.flowcatalyst.ingestor:function-api) and the framework (framework-http) as
provided, and deploy the jar: fcdev fn deploy hello.greeting target/function-hello-0.1.0.jar --create.
The runtime is chosen from the .jar extension. A jar cannot run under fcdev fn run or fcdev fn dev.
See Publish, promote and use aliases for the rest.