Functions

A function is an app's own code that runs on OpenBelt, not in the browser: functions/<name>.js, listed in openbelt.json "functions". Use one for what a page can't be trusted with (a capacity, a check of who is calling), for logic other apps and agents should call instead of copying, and for anything that needs a key, the network or nobody's page open.

{ "functions": { "rsvp": "RSVPs the caller to a meetup. input { event }; returns { spots }" } }
// functions/rsvp.js
export default async ({ event }, { db, caller }) => {
  if (caller === null) throw new Error("sign in to RSVP")
  const meetup = await db.collection("events").get(event)
  const spots = meetup?.data.spots ?? 0
  if (spots < 1) throw new Error("this meetup is full")
  await db.collection("events").update(event, { spots: spots - 1 })
  await db.collection("rsvps").set(`${event}:${caller.email}`, { event })
  return { spots: spots - 1 }
}

Twenty people RSVPing for the last 8 spots at once get exactly 8: a run is all or nothing, so this plain read, check, write needs no locks.

Writing one: a file and a line in openbelt.json

ctx: what a function gets

// functions/ready.js: tell the person who ordered that it's ready
export default async ({ order }, { db, notify }) => {
  const { customer } = await db.collection("orders").get(order)
  return notify(customer, {
    title: `Order ${order} is ready`,
    body: "Pick it up at the front desk",
    path: `/?order=${order}`,
  })
}

Keep no state in module variables: the sandbox is reused and dropped at any time. An app's functions share their code's sandbox within an environment, each file its own module. Live and each preview have separate module state, as do different apps and workspaces. An idle sandbox can be evicted to make room for other apps or versions; the next call loads its code again. Neither eviction nor reuse is a place to keep a caller's private data.

A run is all or nothing

A run's writes commit together when it returns; a throw or a limit writes nothing. If a document it read, or a collection it listed, changed before it commits, it runs again on the new data (up to 6 attempts; ctx.run.attempt counts). A throw is judged the same way: a run that throws after what it read changed runs again, so the error a caller gets is about the data as it is. While a run runs again, new runs of the app wait for it (2 seconds at most), which lets it commit.

// functions/join.js: RSVP (atomic, may re-run), then email (once)
export default async (input, { call, caller, secrets }) => {
  const { spots } = await call("rsvp", input)
  await fetch("https://mail.example.com/send", {
    method: "POST",
    headers: { authorization: `Bearer ${secrets.MAIL_KEY}` },
    body: JSON.stringify({ to: caller.email, event: input.event }),
  })
  return { spots }
}

Queries: read-only, and live on pages

"kind": "query" makes a function read-only (no writes, fetches, call or later), and pages can watch it:

const stop = db.query("attendees", { event }).watch((list) => render(list))
const once = await db.query("attendees", { event })
db.app("meetups").query("attendees", { event }).watch(render) // another app's

Contracts: input and output schemas

input and output are JSON Schemas (type, properties, required, items, enum, const, anyOf, minimum, maximum, minLength, maxLength, minItems, maxItems, additionalProperties, description):

{
  "functions": {
    "rsvp": {
      "description": "RSVPs the caller to a meetup",
      "input": {
        "type": "object",
        "properties": { "event": { "type": "string" } },
        "required": ["event"]
      },
      "output": { "type": "object", "properties": { "spots": { "type": "integer" } } }
    }
  }
}

Calling one: pages, other apps and agents

Secrets, network and connections: the outside world

A function reaches only what openbelt.json grants, and OpenBelt makes, logs and counts each call:

{
  "functions": { "join": "RSVPs the caller and emails a confirmation. input { event }" },
  "network": ["mail.example.com"],
  "secrets": { "MAIL_KEY": "the mail service's API key" },
  "uses": { "deepwiki": "answers questions about a repo's code" }
}

Schedules, webhooks, triggers and later: runs nobody calls

{
  "schedules": { "reminders": { "cron": "0 9 * * *", "timezone": "Europe/London" } },
  "webhooks": { "tickets": { "verify": "hmac-sha256" } },
  "triggers": { "welcome": { "on": "add:rsvps" } }
}

These runs have caller: null, and via says what started them. A webhook's, a trigger's or an internal function can't be called directly (a page, another app, call_function, execute: 403 not_callable) and has no tool of its own: test it as below. A scheduled one can be, like a "refresh now" button; your own code's call and later reach any of them.

// functions/tickets.js: the webhook replies at once; functions/triage.js does the slow part
export default async ({ body }, { db, later }) => {
  await db.collection("tickets").set(String(body.id), { ...body, state: "new" })
  await later("triage", { id: String(body.id) }, { in: "1s", key: String(body.id) })
  return { ok: true }
}
// functions/followup.js, booked with later("followup", { event }, { in: "1d", key: event })
export default async ({ event }, { db }) => {
  const meetup = await db.collection("events").get(event)
  if (meetup?.data.cancelled) return { skipped: true }
  await db.collection("followups").set(event, { event, sent: false })
}

Testing without waiting

Limits

Source: docs/functions.md on GitHub