Inside Barua Functions
What happens when you hand us a repository, what runs when a call arrives, what we keep and what we throw away. Each part, drawn.
From a repository to a URL
You name a repository. We fetch it, compile it, and keep one file: a WebAssembly module. That file answers at a URL that belongs to your organisation.
What your repository needs
Very little. A program that reads its input on stdin and prints its answer on stdout, with the one file that tells us which language it is. Everything else in the repository is ignored.
The smallest working function - Rust
# Cargo.toml
[package]
name = "greet"
version = "0.1.0"
edition = "2021"
// src/main.rs
use std::io::{self, Read, Write};
fn main() {
let mut input = String::new();
io::stdin().read_to_string(&mut input).ok();
let name = input.trim();
write!(io::stdout(), "{{\"hello\":\"{}\"}}", if name.is_empty() { "world" } else { name }).ok();
}
The same in Go
// go.mod
module greet
go 1.22
// main.go
package main
import ("fmt"; "io"; "os"; "strings")
func main() {
in, _ := io.ReadAll(os.Stdin)
name := strings.TrimSpace(string(in))
if name == "" { name = "world" }
fmt.Printf("{\"hello\":%q}", name)
}
barua.json - optional, for the API tab
{
"name": "Greet",
"operations": [
{ "name": "Say hello", "description": "Greets whoever you send.", "body": "Asha" }
]
}
A crate that is also a server
One repository can be both: the HTTP server on a real machine, and a function here. Keep the server's dependencies out of the function's build with a target condition, and pick the entry point by target. This is how pasaka-api is laid out.
# Cargo.toml
[dependencies]
serde_json = "1" # compiled everywhere
[target.'cfg(not(target_os = "wasi"))'.dependencies]
axum = "0.8" # only on a real OS
tokio = { version = "1", features = ["full"] }
sqlx = { version = "0.8", features = ["postgres", "runtime-tokio-rustls"] }
// src/main.rs
#[cfg(target_os = "wasi")]
fn main() { function::run() } // stdin → stdout
#[cfg(not(target_os = "wasi"))]
#[tokio::main]
async fn main() { server::run().await } // the HTTP server
Rules of thumb: read all of stdin, print the answer, exit 0 - a non-zero exit is reported to the caller as a failure. Nothing that opens a socket or a file will work inside the function; a database goes through DATABASE_URL and the host.
What happens to your code
The build runs in a scratch folder that exists only for that build. When it ends, success or failure, the source and every build artifact are deleted. What survives is the module, the compiler's log, the commit hash and the address of the repository.
A call, step by step
A request reaches barua.tz, which checks your API key and asks the runtime on the Tanzania box. The runtime gives the call a brand-new sandbox: your body on stdin, your environment variables, and nothing else of the machine. Whatever the function prints is the response.
Awake and asleep
A function is a server that costs nothing while nobody calls it. The first call starts a warm instance; calls keep it warm; ten minutes of silence retire it. The next call wakes it with a cold start of a few milliseconds, which the page counts.
Your database, through the host
The sandbox has no network, so the function asks the host. Set DATABASE_URL in its environment; your code calls barua_fn::query; the host runs the statement over a connection it keeps warm and hands the rows back into the sandbox as JSON. A Barua database in the same region shares the box, so a query is a few milliseconds.
The API tab
A barua.json next to your code lists what the function can do: a name, a line, the body to send. We keep it with the module, and the API tab turns each entry into the exact request to copy, with your key filled in, and a Try button.
The contract, exactly
Three things decide how comfortably you can build a real application here: what the request looks like from inside, how the database is exposed, and how what you print becomes an HTTP response. Here is each, precisely.
1 · The request, from inside
The body is stdin, byte for byte. No envelope, no JSON wrapping, no re-encoding: the bytes the caller sent are the bytes you read. A GET has an empty stdin. The limit is 256 KB.
Everything else is in the environment, set for that call only:
| Variable | Holds | Example |
|---|---|---|
BARUA_METHOD | the HTTP method | GET |
BARUA_PATH | the path under the function's URL, / when none | /books/45 |
BARUA_QUERY | the raw query string, no ? | lang=sw&q=upendo%20wa |
BARUA_CONTENT_TYPE | the request's content type, or empty | application/json |
BARUA_HEADERS | the caller's headers as a JSON object, lower-cased; never authorization or cookie; up to 8 KB | {"accept":"application/json"} |
BARUA_SOURCE | where the call came from | url, console, api |
BARUA_FUNCTION | the function's id on the runtime | e4be5be8-pasaka |
In Rust, barua_fn::request() reads them into a struct with segments(), query_param("q") (decoded) and header("accept"). A call from the console, or straight at the runtime, is a POST to / with no headers.
use barua_fn::request;
let req = request();
match (req.method.as_str(), req.segments().as_slice()) {
("GET", ["books", id]) => book(id),
("POST", ["books"]) => create(&body),
_ => not_found(),
}
2 · The database, from the SDK
pub fn query(sql: &str, params: &[Value]) -> Result<Vec<Row>, Error> // rows as JSON objects
pub fn execute(sql: &str, params: &[Value]) -> Result<(), Error> // for the effect
pub fn query_one(sql: &str, params: &[Value]) -> Result<Option<Row>, Error>
pub fn query_as<T: DeserializeOwned>(sql: &str, params: &[Value]) -> Result<Vec<T>, Error>
- Parameters are
$1,$2… bound to the JSON values you pass:json!("Asha"),json!(45),json!(true),Value::Null. - Rows come back as JSON objects keyed by column. Numbers, text, booleans and null are themselves;
timestamptzis an ISO string;int8is a string (JSON cannot hold it);byteais base64;jsonbis the JSON itself. - Any statement works:
SELECT,INSERT … RETURNING, DDL. Several statements in one string are fine when there are no parameters. - A transaction is one string:
"begin; …; commit;". If a statement inside fails, the whole thing is rolled back and you get the error; abeginwithout itscommitis rolled back too. Calls have no connection affinity, so a transaction cannot span two calls. - Errors are
Error(String)with Postgres's own message:duplicate key value violates unique constraint "users_email_key". Match on the text if you need to. - Limits: 4 seconds per statement, 4 MB per answer. The host keeps a pool of four connections per
DATABASE_URL, warm across calls. - Natively (a
cargo runof the same crate) every call returnsError, so the server build keeps its own client.
3 · From what you print to an HTTP response
| Your function | The caller gets |
|---|---|
| exits 0, printed something | 200, the body exactly as printed. Content type application/json if it starts with { or [, else text/plain. |
| exits 0, printed nothing | 200 with an empty body |
called status(404), printed something | 404 with your body, and the same for any status 100–599. The run counts as successful; it is your answer. |
called header("content-type", "text/csv") | that content type. Also allowed: cache-control, location, content-disposition, content-language, etag, vary, any x-…. Up to 16. |
| exits non-zero (a Rust panic exits 101) | 500, {"error":{"code":"function_failed","message":<stderr>,"exit":101}}. What you printed is discarded; what you wrote to stderr is the message. |
| runs past 5 seconds | 504, {"error":{"code":"timeout"}}; the instance is replaced |
Every answer carries x-fn-ms (how long the run took), x-fn-exit and x-fn-cold (1 when this call woke the function). Before your code runs, the URL itself can answer 401 invalid_key, 404 function_not_found, 409 function_not_ready (still building, or the last build failed), 413 input_too_large, or 429 rate_limited (600 calls a minute per key).
The rule that follows from this: an application error is your answer, so exit 0 and say it - status(404) and a JSON body, or {"success":false,"error":"…"} at 200 if you prefer one shape. Exit non-zero only when the function itself is broken; that is what turns into a 500. A worked example of all of it lives in hello-barua-fn/echo.
What we record
Enough to run the thing and show you what it did, and no more.
What deleting removes
Delete a function and the runtime removes its module, settings, environment, call log, events and usage at once; its records in barua.tz go with it. Its URL stops answering immediately. Your repository is untouched, as it always was.