Barua /Docs/Functions/Inside
Drawn

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.

Your repository Rust or Go · stdin in, stdout out We build it clone · cargo / go · ~4–20 s One module function.wasm Your URL barua.tz/api/fn/… yours, read-only on the box in Tanzania kept · 60 KB to 4 MB needs one of your API keys
The whole journey. Press Deploy again and it runs again from the current commit; we never watch or write to the repository.

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.

Rust your-function/ ├─ Cargo.tomlrequired · a [package] with a binary ├─ src/ │ └─ main.rsrequired · reads stdin, prints stdout ├─ barua.jsonoptional · the API tab's operations ├─ Cargo.lockwelcome · pins your dependencies └─ Dockerfile, .env…ignored dependencies must compile for wasm32-wasip1 a library crate has nothing to run Go your-function/ ├─ go.modrequired ├─ main.gorequired · package main ├─ barua.jsonoptional · the API tab ├─ go.sumwelcome └─ anything elseignored the standard library needs nothing else · no cgo, no listening sockets · GOOS=wasip1 must compile
If the program lives in a sub-folder (a monorepo, or one repository holding several functions), set the Folder field when you deploy; we look for these files there.

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.

The build, in a scratch folder builds/dep_52a57f3cfa4a/ 1 · shallow clone 2 · compile to wasm 3 · read barua.json, if any nothing reads the code but the compiler one build at a time; no other tenant's build is in this folder Kept, with the function function.wasm the compiled module build.log what the compiler said repo · branch · commit · barua.json Deleted the moment the build ends src/ the clone - your code target/ every intermediate artifact success or failure · never scanned, indexed or trained on
Your code passes through; it does not stay. Today's builds are public repositories, so we hold no credentials of yours either.

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.

Your app POST + Bearer key barua.tz key → your org · rate limit token Runtime · Tanzania box · :8443 awake? no → start an instance (~3 ms, counted as a cold start) A fresh sandbox, for this call only stdin ← your request body env ← the variables you set stdout → the response no network · no filesystem · no other tenant own memory, thrown away afterwards stopped at 5 s if it runs away log one line: who called, how long, exit, bytes, queries bump this hour's counters · reset the idle clock stdout comes back as the body x-fn-ms · x-fn-exit · x-fn-cold the answer
Two calls never share memory, and a crash ends one call, not a neighbour. The runtime's own token never leaves the server side.

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.

Asleep no instance · costs nothing Awake warm instance · code in memory a call arrives → cold start, ~3 ms 10 minutes of silence → idle sleep every call keeps it warm also back here after a new build or an environment change
The Overview's dot breathes while awake and goes quiet while asleep; the Usage tab draws the calls by the hour.

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 same box in Tanzania Your function query("select …", &[…]) no sockets of its own waits while the host works The host reads DATABASE_URL from the function's environment keeps the connection pool Your database br-….pg.barua.app Postgres · yours ~5 ms for four queries SQL rows query rows
Only the database you named is reachable. Each call's line in Activity says how many queries it ran.

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.

barua.json · in your repo { "operations": [ { "name": "A verse", "body": { "book": 43, … } }, { "name": "Search", … } ] } build kept with the module The API tab · one card per operation curl -X POST barua.tz/api/fn/… \ -H "Authorization: Bearer barua_…" \ --data '{"book":43,…}' Copy · Try → the answer in its own window
Keys are stored hashed and shown once, so the tab lets you paste one, or make one for the function, and fills every example with it.

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:

VariableHoldsExample
BARUA_METHODthe HTTP methodGET
BARUA_PATHthe path under the function's URL, / when none/books/45
BARUA_QUERYthe raw query string, no ?lang=sw&q=upendo%20wa
BARUA_CONTENT_TYPEthe request's content type, or emptyapplication/json
BARUA_HEADERSthe caller's headers as a JSON object, lower-cased; never authorization or cookie; up to 8 KB{"accept":"application/json"}
BARUA_SOURCEwhere the call came fromurl, console, api
BARUA_FUNCTIONthe function's id on the runtimee4be5be8-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>

3 · From what you print to an HTTP response

Your functionThe caller gets
exits 0, printed something200, the body exactly as printed. Content type application/json if it starts with { or [, else text/plain.
exits 0, printed nothing200 with an empty body
called status(404), printed something404 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 seconds504, {"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.

Every call when · console, URL or API how long · exit code · cold or warm bytes in and out · queries run up to 500 chars of stderr not the body itself newest 1,000 lines, on the runtime Runs from barua.tz console runs and URL calls a preview of the input, ≤ 1 KB a preview of the output, ≤ 4 KB so Activity can show what was asked in your organisation's records Usage and settings calls, failures, compute · per hour kept for a week · drawn on Usage environment variables · on the box seen by your admins; members see names only builds: log, commit, size, timing
Members of your organisation see the function, its logs and usage. Only admins see environment values, deploy, or delete.

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.

Delete Gone from the runtime and from barua.tz function.wasm · settings · environment · call log events · usage · the function's row and its runs Your repo untouched
Build logs of past deployments are the one thing that still lingers on the box after a delete; we are closing that gap.
Barua Functions · Open Functions · How to use it Example repository Built in Dar es Salaam