01Where a handler lives
A job has two halves. The declaration in the contract says what starts it and who may call it. The handler on the server is its code. A small registry ties them together.
contract/src/index.ts const review = job('review', { … }) declaration
server/src/jobs/review.ts export default handler(c, 'review', fn) code
server/src/index.ts export default server(c, { jobs: { review } }) registry
The registry must list exactly the jobs and flows of the contract, no more and no fewer. A mismatch is caught four times: by the type checker, by the server build, by the trial run during deployment, and when the gateway starts. The file layout is a convention; only the registry matters.
The whole server of an app is bundled into one file and runs as one worker in workerd, the open-source Cloudflare Workers runtime, in a process of its own. It has no network and no disk of its own; everything it reaches goes through the gateway.
02Anatomy of a handler
The job review lets a manager approve or reject a leave request. Its declaration says that only the manager sub-role may call it, with an id and a decision, and that it answers with ok and the new state.
import { handler } from '@astondb/contract/server'
import c from '@leave/contract'
export default handler(c, 'review',
async (body, env, run) => {
if (!body || !run.user) return { ok: false }
const [req] = await env.RECORDS.teamRequest
.list({
where: { id: { eq: body.id },
manager: { eq: run.user.email } },
limit: 1,
})
if (!req || req.state !== 'new') {
return { ok: false }
}
const state = body.approve
? 'approved' : 'rejected'
const n = await env.RECORDS.request.update(
{ id: req.id }, { state },
{ ifMatch: { state: 'new' } })
if (n === 0) return { ok: false }
await env.EVENTS.emit('request', req.id)
console.log('decided', { id: req.id, state })
return { ok: true, state }
})
- This is the code of the job review of contract
c. The types of the input and of the answer come from the contract; nothing is generated. - No input or no person? Then there is nothing to do.
- The gateway already checked that the caller is a manager. The code checks that the request belongs to their team.
- Change the state, but only if it is still
new. If someone else was faster, nothing changes and the job says so. - Announce the change, so jobs listening to the table can react.
- Write a log line and return the declared answer.
From the browser the call is one line, api.review({ id: 7, approve: true }), using the typed client from @astondb/contract/client. On the wire it looks like this:
POST /leave/api/review
Cookie: __Host-aston-session=…
X-Aston-CSRF: 1
{ "id": 7, "approve": true }
→ 200 { "ok": true, "state": "approved" }
The handler always gets three arguments, (body, env, run). They are plain arguments, not global variables, so the type checker can follow them.
| Argument | What it is |
|---|---|
body | The input from the web API after validation. Empty for runs without input. |
env | The platform's tools: data, SQL, events, files, secrets, flows, other apps. The same for every run. |
run | What belongs to this run: the person, if any, and what started it. |
03body: the input
- Its type is the job's
api.inputfrom the contract. - It may be empty. The same handler also runs for a schedule, an event, a manual run by the admin or a queue re-run, and those have no input. Its type is therefore "input or
undefined", and checking the trigger does not change that. Start every web job withif (!body) return. - It is validated twice. The gateway checks the request against the JSON Schema of
api.inputbefore the run (400on failure), and the worker parses it again before calling the handler. - Extra fields are dropped, not refused. The handler never sees fields the contract does not declare.
- Only the input arrives. HTTP headers never reach the job, not even filtered.
04run: who and why
| Field | What it is |
|---|---|
run.user | { email, name, roles } of the person whose roles decided the run: the caller of a web API with a session, including a call from that person's AI assistant over MCP, or the person on whose behalf another app called this job. roles are this app's sub-roles without the prefix, like ['manager']. It is null for schedules, events, manual runs, re-runs, calls with an API key and calls of an asApp job from another app: then the run acts for the app. |
run.trigger | What started the run. Check run.trigger.source first; each source has its own fields. run.trigger.user, where present, is who caused the run, even when the run acts for the app. It is not a permission: it carries no roles. |
source | Other fields |
|---|---|
api | user: { id, email } for a call with a session, also from the person's AI assistant, or key: the name of the API key for a call from another system |
cron | expression and scheduledAt, the planned time in milliseconds, useful to compute "since the last run" |
event | table, operation (create, update, delete), id, pk (the full key), emitter (the job that emitted it, or null for an operation); for an event of another app also app, the source app |
app | app: the app that called this job through env.APPS or env.ASYNC; user?: { id, email }: who caused the caller's run, when anybody did; async: true when nobody is waiting for the answer |
manual | user: { id, email } of the admin who pressed "run". The run acts for the app, as on schedule |
dirty | nothing: a re-run the queue scheduled because the job was busy |
continue | the answer of an async call, for a job declared with continue: job and run, the job and the run that started the wait, from (fetch or call) and, for a call, target, the app the answer came from |
05What a handler returns
- With
api.output, the handler should return exactly that shape. It is what the frontend's types and the AI tool schema are built from, and typecheck holds the two sides together — but on the web path the gateway does not inspect the answer, it streams it to the caller as it comes. The shape is checked where a value enters another app, inenv.APPS.call. - Without
api.output, the answer is sent as it is. - An exception the job did not plan is a
500. The caller gets the status and nothing else; the message and the stack stay in the log, because a crash is not a sentence anybody outside should read. - A refusal the job did plan is a
JobError. “Somebody approved this an hour ago” is an answer, not a breakdown. The job throws it with a status, a sentence and, if it helps, an object — and that is what the caller receives. - Schedules and events have no caller. Their return value only shows up as the job's last result in the admin.
Refusals the job means: JobError
Almost every job has an answer that is neither data nor a crash: the record is gone, the state moved while the person was reading the screen, a limit was reached. JobError is how the job says so, and it is the only way a sentence the job wrote reaches the caller at all.
import { handler, JobError } from '@astondb/contract/server'
export default handler(c, 'review', async (body, env, run) => {
const [r] = await env.RECORDS.teamRequest.list({
where: { id: { eq: body.id }, manager: { eq: run.user!.email } }, limit: 1,
})
if (!r) throw new JobError(404, 'request not found', { id: body.id })
if (r.state !== 'new') throw new JobError(409, 'request is already decided', { state: r.state })
const state = body.approve ? 'approved' : 'rejected'
const n = await env.RECORDS.request.update({ id: r.id }, { state }, { ifMatch: { state: 'new' } })
if (n === 0) throw new JobError(409, 'request was decided by someone else')
return { ok: true, state }
})
The caller of that second line gets exactly this, and a frontend can draw it without a lookup table of its own:
409 { "errors": [ { "message": "request is already decided", "detail": { "state": "approved" } } ] }
| Status | When a job gives it |
|---|---|
400 | the input parses but makes no sense: a range that ends before it starts |
404 | what the input points at does not exist, or is not the caller's to see |
409 | the state of the record does not allow it, or somebody else got there first |
422 | the input passed the schema but breaks a rule the schema cannot express |
429 | something behind the job refused for now, and trying later is the right answer |
- Five statuses, checked by the gateway. Not by the job's own process, which the app's author controls. A status outside the list, an empty message or a
detailthat is not JSON is a failed run: the caller gets a plain500and the reason is in the log. 401and403are the platform's to give. Across the whole platform they mean “the gateway decided” — the session, the CSRF header, access to the app,owner, a permit — and an admin debugging permits must be able to trust that. A domain “not your team” is a404, which is also the better answer:403admits the record exists.5xxis a statement about the platform, not about the request, so a job never gives one either.- The message is for a person, the
detailfor the screen. One sentence in English, and any JSON you like beside it, up to 1 MB. The frontend branches on the status and usesdetailto say which field, which row, which limit. - It travels the whole way. To the browser as the platform's own error shape; to a calling app as an
AppCallErrorwith the same status; to an async continuation aserror.kind: 'call', which is how a deliberate refusal is told apart from a run that fell over. In a flow step it takes the error edge, and from a schedule or an event, where there is nobody to tell, it simply fails the run — as a warning in the log, not an alarm. - A refusal from another app is not yours to pass on. Catch the
AppCallErrorand decide what it means for your caller. Re-throwing its status blindly fails the run, because the statuses other layers use are not in the list. - Check what you can before the first write. A job that has already written and then throws keeps what it wrote; the platform does not roll a run back. What can be checked up front belongs up front — and for the rest there is
ifMatch, whose0changed rows is exactly the409above.
It does not replace a return value. What the caller handles as a normal outcome, even a negative one, stays in the answer: “these dates overlap another holiday” is data the form draws. What cancels the work is a JobError. Move everything into exceptions and the frontend ends up with a try around every call, while the contract stops saying anything.
Commands: answers the gateway builds
A job declared with api.command: true may return a command instead of data. The job decides what, the gateway decides how: it runs the command after the job finishes and streams the result straight to the caller. Large data never passes through the job, so the 1 MB answer limit and the 30-second run limit do not apply; a command has 5 minutes.
| Helper | The caller receives |
|---|---|
json(query) | the rows of a select as a JSON array |
csv(query, { file }) | a CSV file: ; separator, UTF-8 with BOM, a header row, cells that look like formulas are defused |
xlsx({ file, sheets }) | an Excel file with one sheet per select; text is always text, never a formula |
attachment(id, { name? }) | a file from one of the app's buckets |
A query is always a fragment written with env.DB.sql`…`, never a string, so a command cannot carry SQL injection either. A job with commands may still return plain data, which goes out as JSON. A command returned by a schedule or an event fails the run, because there is nobody to deliver it to.
Bytes of your own: returning a Response
A job with api.command: true may also return a Response and produce the body itself, chunk by chunk: an export assembled from several sources, a conversion, the tokens of a model as it writes them. The 1 MB answer limit does not apply, because the bytes never sit in one envelope.
export default handler(c, 'generate', async (body, env) => {
const it = tokens(body.topic)
return new Response(new ReadableStream({
async pull(ctrl) {
const { value, done } = await it.next()
done ? ctrl.close() : ctrl.enqueue(new TextEncoder().encode(value))
},
cancel: () => void it.return?.(), // the client went away
}), { headers: { 'content-type': 'text/plain; charset=utf-8' } })
})
- Produce the stream in
pull, which the consumer calls, so back-pressure works by itself and a slow client puts the job to sleep. A loop that keeps callingenqueuepiles the chunks up in memory instead; it is a bug that a review does not see. - The run lasts until the last byte, so
env.DBand calls outwards still work while the stream flows — and the run's time limit covers the whole of it. - 2xx and three headers are yours:
Content-Type,Content-DispositionandContent-Length. An error status does not come from theResponse; it comes from aJobErrorthrown before the first byte, while there is still nothing on the wire to interrupt. - A failure after the first byte cannot be reported: the stream is cut, the status is already sent, and the reason is in the log. A caller can only tell a cut stream from a whole one when the job declared
Content-Length, so a body of known length is worth the trouble. - Only a caller can receive it. From a schedule, an event, a flow step or a continuation, returning a
Responsefails the run. In the browser, the typed client hands it over untouched with{ raw: true }.
Answers that come later: env.ASYNC
Some answers do not fit inside a run: a model that writes for minutes, another app whose work takes an hour. env.ASYNC hands the call over and the run ends without waiting for it. The answer of a run is still its return value — it is only allowed to be produced by a later run.
// the app that asks: this run ends here and waits for nothing
await env.ASYNC.call('llm', 'chat', { model: 'sonnet55', messages }, {
job: 'answerReady', // my own job, which will take the answer
state: { requestId: 7, who: run.user.email }, // my context; it never leaves my app
timeout: '1h',
})
// the app that answers: it checks the credit in its own run and returns a command, not a value
export default handler(c, 'chat', async (body, env, run) => {
if (!(await hasCredit(env, run.trigger.app))) return { ok: false, reason: 'no credit' }
return env.ASYNC.fetchToJob({ // “my answer will come from here”
request: { url: 'https://api.example/v1/messages', method: 'POST',
headers: { 'x-api-key': env.SECRETS.LLM_KEY }, body: JSON.stringify({ … }) },
job: 'modelAnswered', state: { app: run.trigger.app },
})
})
// its own continuation: it books what the call cost and returns the value
export default handler(c, 'modelAnswered', async (body, env) => {
if ('error' in body) throw new Error(body.error.message)
const answer = JSON.parse(body.response.body)
await env.RECORDS.usage.insert({ app: body.state.app, tokens: answer.usage.output_tokens })
return { text: answer.content[0].text } // this is what the first app receives
})
// the first app's continuation, two runs later
export default handler(c, 'answerReady', async (body, env) => {
if ('error' in body) { … ; return } // timeout, failure, refusal
const { text } = body.value as { text: string }
await env.RECORDS.request.update({ id: body.state.requestId }, { text })
await env.PUSH.send(body.state.who, { type: 'llm.done', id: body.state.requestId })
})
- Four calls in two positions.
await env.ASYNC.call(…)andawait env.ASYNC.fetch(…)start a chain beside the run, which still answers with its own value;return env.ASYNC.callToJob(…)andreturn env.ASYNC.fetchToJob(…)say “my answer comes from there”. A command that is made and not returned fails the run, so it cannot quietly do nothing. Without ajobthe chain simply ends: fire and forget. - Nothing of yours travels to the other side.
statestays in the waiting row on your side: the other app does not see it, cannot change it and cannot answer twice. There is no token to call you back with, no new edge in the graph of apps, and no new kind of permit — the target needs the samepermits.apias a direct call, and must be a job withapi.asApp, because a wait of hours has no person in it. An address forfetchneeds the sameegresspermit as the job's ownfetch. - The chain is the same mechanism one floor down. Whatever the called job returns is your answer — a value, or another async command, as in
chatabove. The last run of the chain is checked against theapi.outputof the job you called, so a value out of shape reaches you as anerrorinstead of nonsense. A refusal the called job meant arrives aserror.kind: 'call'with its message and itsdetail, apart from the'failed'of a run that broke. Up to five links, shared with the chain of events. - The called run goes through the queue, like an event: its own
maxConcurrencyholds, and it gets a full queued run's time instead of the rest of yours. The continuation runs outside the queue, so an answer is never dropped. - A continuation acts for the app:
run.userisnull, because the person's session may be long gone. Carry whoever is waiting instate, as above. The one exception is afetchwith nobody waiting on its value: that wait lives in memory for minutes, so it keeps the person of the original run. - It always ends.
timeoutis an hour by default and twelve at most, and then the continuation getserror.kind: 'timeout';env.ASYNC.cancel(id)ends a wait of your own early. A restart kills a call outwards in flight: whoever was waiting on its value is told, and otherwise it is lost quietly. Keep the state of the task in your own data and recognise an unfinished one by its age. For waiting that lasts days, or on a person, there is a flow.
06The toolbox: env
Everything a job can do with the platform is in env, with upper-case names like bindings in Cloudflare Workers. Apart from it a job has only console and fetch.
| Tool | What it is for |
|---|---|
env.RECORDS | Create, read, update, delete and list on every record of the contract. |
env.DB | Raw SQL in the app's schema, for joins, sums and bulk changes. |
env.EVENTS | Announce that a row changed, so other jobs react. |
env.FILES | Files in the app's buckets, and signed links for the browser. |
env.SECRETS | Settings and secrets the contract names and the admin has set. |
env.OAUTH | Access tokens for outside APIs, produced by the gateway. |
env.FLOWS | Start, wake and cancel long-running flows. |
env.APPS | Jobs and operations of other apps, platform views and the person's token, each with a permit. |
env.ASYNC | A call outwards or into another app that the run does not wait for; the answer arrives in a later run. |
env.PUSH | A short message to a person's open browser, when a job has finished something they are waiting for. |
env works only inside a run. Calling it at the top level of a module throws. Each call carries a token of the current run, and the gateway takes the app and the person from that token, never from the worker, so a job can neither pose as another app nor slip in another person.
07env.RECORDS
const rows = await env.RECORDS.request.list({
where: { state: { eq: 'new' }, from_date: { gte: '2026-10-01' } },
sort: ['-from_date'], limit: 50, offset: 0,
}) // rows
const req = await env.RECORDS.request.read({ id: 7 }) // row or null
const { id } = await env.RECORDS.request.insert({
author, from_date, to_date, state: 'new', note: null,
}) // the new key
const n = await env.RECORDS.request.update(
{ id }, { state: 'approved' }, { ifMatch: { state: 'new' } }) // rows changed
await env.RECORDS.request.delete({ id }, { ifMatch: { state: 'new' } }) // rows deleted
- Every record, all five actions. Tables that are not records, and the platform's tables, are out of reach here; use
env.DB. - The rules of operations do not apply. A job exists precisely to write what users may not write themselves, so
where,setandcheckfromopsare ignored and every row is visible. Columns that an operation fills from the session, likeauthor, the job fills itself, typically fromrun.user. - Conditions use
eq ne gt gte lt lte in is_null, combined with$and $or $not. There is no session in them; the person is inrun.user. limitis at most 1000, which is also the default. Rows are ordered bysortand then by the key, so paging withoffsetis stable.ifMatchis an optimistic lock. The row changes only if those columns still have those values.0changed rows is an answer, not an error.- Values are checked against the record. An unknown column or a wrong type throws a
DataErrorwith status400. - Each call commits on its own, and none of them emits an event. Writes that must succeed together go through
env.DB.batch. - Big integers and decimals arrive as numbers, JSON columns as plain JSON.
08env.DB
Raw SQL for what records cannot express: joins, aggregates, bulk updates.
const req = await env.DB.select1`SELECT * FROM request WHERE id = ${id}` // row or null
const rows = await env.DB.select`SELECT * FROM request WHERE state = ${'new'}` // rows
const { rowCount } = await env.DB.execute`UPDATE request SET state = ${'x'} WHERE id = ${id}`
const found = await env.DB.select`SELECT * FROM request
WHERE platform.unaccent(note) ILIKE platform.unaccent(${'%novak%'})` // without accents
const typed = await env.DB.select(schema)`SELECT * FROM request` // parsed with zod
await env.DB.batch([ // one transaction
env.DB.sql`UPDATE request SET state = 'approved' WHERE id = ${id}`,
env.DB.sql`INSERT INTO history (request_id) VALUES (${id})`,
])
- Only tagged templates. Every
${…}becomes a query parameter, so SQL injection cannot be written even by mistake. There is no(sql, params)form. - Tables are written without a schema. The app's role searches its own schema.
- A transaction is
batchand nothing else: one call, one commit or rollback. A transaction spread over severalawaits does not exist. - Without a schema, big integers and decimals come back as strings (
Number(r.count)). Withselect(schema)the rows are parsed and converted. - Results are limited to 1 MB, and a statement is cancelled when the run's time is up. Selects run read-only as a safety net.
- Database errors about data (classes 22 and 23) throw a
DataErrorwith status400, a duplicate key409, anything else500. - Writes through
env.DBemit no events either.
| Object | What env.DB may do with it |
|---|---|
| the app's own schema | everything its owner may: tables of records, and any other tables, views and functions from the app's migrations |
platform.unaccent(text) | call it, for searches that ignore accents |
| the rest of the platform | nothing: permission denied. People and apps come through $view |
| other apps' schemas | nothing |
The boundary is the database role of the app, not a check of the SQL text.
09env.EVENTS
await env.EVENTS.emit('request', id) // request.update
await env.EVENTS.emit('request', id, 'create') // request.create
- The first argument is the table, not the record. Two records over one table share their events.
- Operations emit events by themselves; jobs must emit explicitly. Writes through
env.RECORDSandenv.DBare silent. - Events are how jobs chain. A job cannot call another job of its own app; it emits an event the other one listens to. A chain is at most 5 links deep, also across apps: a job at depth 5 gets an error from
emit. - Re-read the row in the listening job. The run may have waited in the queue and the row may have changed meanwhile.
- Other apps may listen too. A job of another app subscribed to
leave:request.creategets the event when its app has a permit for it. It runs for its app, seesrun.trigger.appand only the key; to read the row it calls this app with anapipermit.
10env.FILES
await env.FILES.put('attachments/2026/r-42.pdf', body,
{ name: 'request.pdf', contentType: 'application/pdf' }) // { id, size }
const f = await env.FILES.get('attachments/2026/r-42.pdf') // file or null
await env.FILES.delete('attachments/2026/r-42.pdf') // true or false
const { objects, cursor } = await env.FILES.list({ prefix: 'attachments/2026/', limit: 100 })
const up = await env.FILES.sign({ write: 'attachments', ttl: 600, maxCount: 1 }) // upload link
const rd = await env.FILES.sign({ read: 'signatures/x.pdf', ttl: 3600 }) // read link
const sh = await env.FILES.sign({ share: 'attachments/2026/r-42.pdf', ttl: 600 }) // for another app
- A job may do everything in every bucket of its app: read, write, overwrite, list, delete and sign.
- A file id is
bucket/key. A file has a name, a content type, a size and an upload time. text()andarrayBuffer()read up to 10 MB. Read bigger files as a stream throughbody. One file may be up to the platform's limit (50 MB by default).- The browser writes only through a signed link. A job checks who may upload what, then signs a link with a lifetime (
ttl, 1 second to 24 hours) and optional limits (maxSize,maxTotal,maxCount). The browser uploads withapi.$upload(link, file)and gets the new id back. - The platform does not check where an id came from. A job that passes an id from the input to
attachmentorsignopens that file regardless of the bucket'sread. Check ownership in code first. - A file goes to another app as a share link, not in the body of a call, which has a 1 MB limit. The link starts with
share://, lives up to 24 hours, and a job of any app reads the file withenv.FILES.get(link). Neither a browser norfetchcan open it. Signing it is the decision that the file may leave.
11Secrets and OAuth
// contract: secrets: ['HR_URL', 'HR_TOKEN', 'ERP_BASIC', 'ERP_OAUTH']
const base = env.SECRETS.HR_URL // string or undefined
const auth = `Basic ${env.SECRETS.ERP_BASIC}` // ready base64(user:password)
const token = await env.OAUTH.token('ERP_OAUTH') // access token
const fresh = await env.OAUTH.token('ERP_OAUTH', { maxAge: 0 }) // force a new one, e.g. after a 401
env.SECRETS.HR_TOKN // type error: not in the contract
- The contract names the secrets, the admin sets them. The names are in the contract's
secrets; the values live in the platform's encrypted secure store. For each name the admin enters a value for this app, or points it to a shared entry that several apps use. env.SECRETS.NAMEis the value of a plain setting or the decrypted secret, orundefinedwhen the name has no source. For a username and password the job gets the readybase64(username:password)for aBasicheader.env.OAUTH.token(name)takes only names ending in_OAUTHand returns an access token. The gateway obtains it with the client credentials it keeps and caches it; the app never sees the client secret.maxAgeis0or a duration like'30m'.- Types come from the contract.
env.SECRETShas exactly the contract's names, so a typo does not compile. - A new value applies from the next run. No build, deploy or restart; a run that is going keeps the values it started with.
- Incoming API keys never reach the job. The gateway checks them before the run; the job sees only the key's name in
run.trigger.key. - A value is not a permit. Calling the host in
HR_URLstill needs anegresspermit; the contract may ask for it as{ secret: 'HR_URL' }.
12env.APPS: other apps, people and the person's token
One door to everything outside the app that is not the internet. Every target needs a permit in the contract's permits.api, given by the admin (see the contract guide).
const status = await env.APPS.call('erp', 'orderStatus', { id: 7 }) // a job's output
const orders = await env.APPS.call('erp', 'orders', { limit: 50 }) // an operation's answer
const res = await env.APPS.fetch('erp', 'exportOrders', { year: 2026 }) // a Response, streamed
const team = await env.APPS.call('$view', 'myMembers', {
fields: ['email', 'name', 'role'], where: { role: { eq: 'reports:editor' } },
})
const { accessToken } = await env.APPS.call('$idp', 'accessToken', {})
Jobs and operations of other apps
- As the person, unless the target says otherwise. An operation, and a job without
api.asApp, run asrun.user: the other app checks the person's role andowner, and an operation applies itswhere,setandcheck, exactly as from its own frontend. Only a run with a person may make such a call; from a schedule it is403. - As the app, when the target allows it. A job declared with
api.asApp: trueruns without a person: in the targetrun.userisnullandrun.triggersays{ source: 'app', app: 'reports', user? }. Any run may call it, also a schedule or a flow step. - Refusals are statuses, not crashes.
callthrowsAppCallErrorwith thestatusand theerrors— a permit that is missing, and equally aJobErrorthe other job meant, with its sentence and itsdetail;fetchreturns theResponseand leavesres.okto you. A job that answers with a command is called withfetch, and its file streams straight intoenv.FILES.put. - One level deep. A job called from another app does not call further apps, and an app cannot call itself.
- Shared limits. The caller waits at most the rest of its own time, so work that takes minutes goes through
env.ASYNCinstead. All calls of a run, together withfetch, count towards 1,000. Each call is a log line of the caller's run. - Types are yours to share. The platform does not generate them: the other app's team hands over a small declaration file that extends the
Appsinterface, and from then on names, inputs and outputs are typed. Without it they areunknown.
$view: people and apps of the platform
- Fixed read-only views, read as the app:
users(e-mail, name),apps,allMembers(people with roles in any app),myMembers(people with a role in this app) andrunUser(the person of the run, with the identifiers from the company login). Each view is a permit of its own. - The body is shaped like
env.RECORDS.list, plusfields:where,sort,limitup to 1,000 andoffset. The answer is an array of rows. The gateway builds the query; no SQL of the app touches the platform. - Any run may read a view, with or without a person.
runUserwithout a person is an empty array.
$idp: the person's own token
accessTokenreturns{ accessToken, expiresAt }, the token the company login issued to the signed-in person, for calling another system in their name.{ maxAge: 0 }forces a new one, for example after a401.- Only a run started by a signed-in person gets it: a web call with a session, a call through their AI assistant, or a call made on their behalf by another app. Schedules, events, API keys and flow steps get
403. When the person's login has ended, the answer is409and the app asks them to sign in again. - The company login must be set up for it. Without that the call is
409, also in local development.
13env.PUSH: a message to the open browser
A web call has to answer in seconds, so anything longer moves to a queued job — and then nothing tells the page that it is done. env.PUSH does: a short message to a named person, delivered to every tab of this app they have open, over one connection the platform keeps for them.
// the queued job, once the work is finished
await env.PUSH.send('jane@acme.example', { type: 'report.ready', id })
// the page, with the typed client
const off = api.$subscribe({
message: (m) => { … }, // whatever the job sent
resync: () => reload(), // messages may have been missed: read the state again
unauthorized: () => api.$login(),
})
- Any run may send, whatever started it: a web call, a schedule, an event, a flow step. The address is an e-mail, because a run from the queue has no caller of its own to answer.
- It reaches this app only. The platform takes the app from the run's token, so a message cannot land in another app's page. The recipient's role is not checked: it goes to whoever the app named.
- Delivery is not promised. Nobody may be connected, the browser may have been asleep, a restart drops what was in flight. The client notices a gap and calls
resync— which is why it is required: the page reads its state again instead of waiting for ever. Keep what matters in the database and treat the message as a nudge, although a result that fits may travel with it, up to 256 KB. - Another app can be allowed to nudge for you.
env.PUSH.grant(email)returns a signed string, valid for an hour by default and a day at most, which the holder may use in place of the address. Pass it to the slow job of another app, and its message appears in your app's page, for that one person. No permit is needed, because the grant carries nothing else: one message, to that one person, in that one app, until it expires — no reading, no writing, no job of yours called. - The page does not manage the connection. One shared worker per origin holds one stream for every tab and every app of that host, reconnects with a growing delay and replays what it still has after a short drop. A browser without shared workers gets an
Errorfrom$subscribeand no live messages. - It is not a notification and not an event. No popup from the operating system, nothing delivered to a closed browser, nothing started on the server: this is a message between a job and a page that is open.
14fetch and console
const res = await fetch('https://erp.acme.example/api/employees', {
headers: { Authorization: `Bearer ${await env.OAUTH.token('ERP')}` },
})
const employees = await res.json()
console.log('synced', { count: employees.length })
fetchis the standard one, withRequest,Responseand streams. Every call goes through the gateway, which allows only thehost:portpairs the admin has permitted, never internal addresses, and at most 1,000 calls per run together withenv.APPS. Anything else is403. A permit taken away applies from the next call.- The job writes its own headers. The platform adds no credentials by itself.
- Files can flow through. Download with
fetchand passres.bodytoenv.FILES.put, or sendfile.bodyout as a request body. - Logging is
console:log,info,warn,error,debug. The lines go to the gateway's log with the app and the job. - npm packages are fine if they can be bundled for workerd and need nothing beyond web APIs and
fetch.
15Flow code and env.FLOWS
The contract holds a flow's graph (see the contract guide). The server holds only the bodies of the steps and the decisions, in flowImpl:
import { flowImpl } from '@astondb/contract/server'
export default flowImpl(c, 'invoicing', {
steps: {
checkCredit: async (ctx, env) => ({ credit_ok: await verifyCredit(env, ctx.order_id) }),
collectPayment: {
async init(ctx, env, run) {
await env.RECORDS.payment.insert({ ref: run.correlationId, amount: ctx.amount, state: 'new' })
},
result: ({ data }) => ({ payment_id: (data as { payment_id: string }).payment_id }),
},
invoice: async (ctx, env) => ({ invoice_id: (await env.RECORDS.invoice.insert({ … })).id }),
cancelOrder: async () => ({}),
},
decide: {
afterChecks: ({ ctx }) => (ctx.credit_ok && ctx.payment_id ? 'invoice' : 'cancelOrder'),
},
})
| Step | On the server | Returns |
|---|---|---|
task() | async (ctx, env, run) => … | changes to ctx |
asyncTask() | init(ctx, env, run) sends the request; result({ ctx, data }) handles the answer | changes to ctx |
subFlow() | input({ ctx }) builds the child's input; optional result({ ctx, data }) | changes to ctx |
fork, join | nothing; they have no body | — |
choose(name, …) | decide[name]({ ctx, via }), a pure function | one of the declared candidates |
- A step runs without a person. Its
envis the job'senvwithoutEVENTS. Throughenv.APPSit may read views and call jobs of other apps markedasApp, like a schedule.run.viasays which edge led here and, after an error, the message. run.correlationIdexists only ininit. Put it into the outgoing request so the other system sends it back; a job then wakes the step with it.- Decisions are pure. They get no
envand may be evaluated again after a crash. - Steps may run twice. After a crash a step can run again, so it should ask the app's data or write with
ifMatch.initis the exception: it is not repeated, and a lostinitends in the timeout edge.
env.FLOWS | Returns | Effect |
|---|---|---|
start(flow, input) | { id } | Creates a run and returns once it is stored, before the first step. |
resume(correlationId, data?) | true / false | Wakes a waiting asyncTask with an answer: result, then the ok edge. |
reject(correlationId, reason?) | true / false | Wakes it with a failure: the error edge. |
cancel(instanceId) | true / false | Ends the run as failed with CANCELLED. |
A step is woken at most once: a late or repeated callback gets false, which means "there was nothing to do", not an error — the same for an instance that does not exist or belongs to another app. None of these calls throw, and none of them cross the app's boundary.
Five more calls read, and a flow step has them as well:
| Reading | Over what | Returns |
|---|---|---|
list(filter?, page?) | running instances, and finished ones the archiver has not taken yet | headers: flow, status, the steps the run stands on, when the run next wakes, who started it, counters and times |
stats(filter?, opts?) | the same | counts over the same filter, grouped |
archive.list, archive.stats | archived instances | the same pair with fewer fields: the archive holds a header, not a live run |
get(id, opts?) | both places | one instance in detail — ctx, threads, waits and the chronicle — with source saying where it was found |
- Two pairs, not one call. A running instance knows things an archived one cannot: a version, and the steps it stands on. One listing over both would have to return those empty, and the caller could not tell "nothing" from "not knowable".
- The filter is platform properties — flow, status, step, parent, who started it, time ranges — never data of the process. To search by your own data, declare
ctxTablein the contract and query your own table, which the platform keeps up to date with every instance's state and ctx (see the contract guide). - An instance is archived once the app has its final state in that table. Its detail — the definition it ran with and the whole chronicle — becomes one object in the file storage, and
getfinds it there without being told.
// The bank calls back with an API key; the job wakes the waiting payment step.
export default handler(c, 'bankCallback', async (body, env) => {
if (!body) return { ok: false }
const ok = body.paid
? await env.FLOWS.resume(body.ref, { payment_id: body.payment_id })
: await env.FLOWS.reject(body.ref, 'payment declined')
return { ok }
})
16Limits and failures
| What | Limit | When it is exceeded |
|---|---|---|
| time of one run | 60 s by default for a web or AI call; 10 minutes for a queued run, a flow step or a continuation | The run ends, the app's process lives on: its token dies, SQL in flight is rolled back, every further call is refused and a web caller gets 504. Only a run that does not react within two further minutes costs the process its life. |
| CPU and memory of the app's process | measured every 2 s | A process over the limit is killed, together with the app's other running runs. Three kills in ten minutes park the app until it is deployed again — the other apps keep serving. |
| request body and answer | 1 MB | 413 for the body; an error for the answer |
| result of one SQL call | 1 MB | an error, not a cut-off |
outgoing calls: fetch and env.APPS together | 1,000 per run | 429 |
| a call to another app | the rest of the caller's time; one level deep | an error for the caller; the called run finishes on its own |
| command (json, csv, xlsx, attachment) | 5 minutes; Excel has up to 1,048,576 rows per sheet | the command fails |
| one file | 50 MB by default | the upload or put fails |
text(), arrayBuffer() | 10 MB | read it as a stream instead |
| chain of events and async calls | 5 links | emit and the call throw with status 400 |
| waiting async calls, waiting async fetches | 100 of each per app | 429 where the call is made; every wait has a deadline, so the budget always clears |
| one async wait | 1 hour by default, 12 hours at most; a fetch itself up to 10 minutes | the continuation gets error with timeout or network |
body of an async call, and its state | 256 KB and 64 KB | 413 for the body, 400 for the state |
detail of a JobError | 1 MB | the caller gets 500; the reason is in the log |
| one push message | 256 KB | send throws |
| moves of one flow run | 1000 by default | the run fails with MAX_STEPS |
504 does not mean that nothing happened. A run that hit the time limit may have written already. Make jobs idempotent and guard writes with ifMatch, so running them twice does no harm.
Other answers the caller can see: 502 when the runtime is not available, and 503 while the app is not running or when a deployment took longer than one run's limit. During a deployment web calls wait instead of failing, while operations, files and commands keep working.
17Recipes
Let the browser upload an attachment
export default handler(c, 'attachmentLink', async (body, env, run) => {
if (!body || !run.user) throw new Error('attachmentLink runs only through api')
const [req] = await env.RECORDS.request.list({
where: { id: { eq: body.id }, author: { eq: run.user.email }, state: { eq: 'new' } },
limit: 1,
})
if (!req) throw new Error('not your request, or no longer new')
return { link: await env.FILES.sign({ write: 'attachments', ttl: 600, maxSize: 5 * 1024 * 1024, maxCount: 1 }) }
})
// browser: const { link } = await api.attachmentLink({ id }); const file = await api.$upload(link, picked)
Accept records from another system
// contract: api: { owner: s.role('integration'), key: 'ERP_INBOUND', input: …, output: t.object({ id: t.int() }) }
export default handler(c, 'intake', async (body, env) => {
if (!body) throw new Error('intake runs only through api')
// a call with an API key acts for the app: run.user is null, so the author comes in the body
const { id } = await env.RECORDS.request.insert({ ...body, state: 'new', note: null })
await env.EVENTS.emit('request', id, 'create')
return { id: Number(id) }
})
Ask another app, as the person
// contract: permits: { api: ['erp/orderStatus'] }
import { AppCallError, handler } from '@astondb/contract/server'
export default handler(c, 'orderInfo', async (body, env, run) => {
if (!body || !run.user) return { ok: false }
try {
// runs in erp as run.user: erp checks the person's role and owner itself
return { ok: true, status: await env.APPS.call('erp', 'orderStatus', { id: body.id }) }
} catch (e) {
if (e instanceof AppCallError && e.status === 403) return { ok: false } // no permit, or no role in erp
throw e
}
})
Be called by another app, as the app
// contract of wiki: api: { owner: s.role('editor'), input: …, asApp: true }
export default handler(c, 'importPages', async (body, env, run) => {
if (!body) return { ok: false }
// from another app there is no person and no owner check: narrow the callers in code if it matters
if (run.trigger.source === 'app' && run.trigger.app !== 'reports') return { ok: false }
// …
return { ok: true }
})
Export the team's requests to Excel
import { handler, xlsx } from '@astondb/contract/server'
export default handler(c, 'exportRequests', async (body, env, run) => {
if (!body || !run.user) return { ok: false }
return xlsx({
file: 'team-requests.xlsx',
sheets: {
Requests: env.DB.sql`SELECT id, author, from_date, to_date, state FROM v_team_requests
WHERE manager = ${run.user.email} AND state = ${body.state}
ORDER BY from_date`,
},
})
})
A morning summary on a schedule
export default handler(c, 'reminder', async (_body, env) => {
const rows = await env.DB.select`
SELECT manager, count(*) AS waiting FROM v_team_requests WHERE state = 'new' GROUP BY manager`
for (const r of rows) console.log('reminder', { manager: r.manager, waiting: Number(r.waiting) })
})
React to a new row
export default handler(c, 'notifyNew', async (_body, env, run) => {
if (run.trigger.source !== 'event') return
const req = await env.RECORDS.request.read({ id: Number(run.trigger.id) })
if (!req || req.state !== 'new') return // it may have changed while the run waited
console.log('new request', { id: req.id, author: req.author })
})
18Testing
Handlers are tested in workerd, built by the same step as the production bundle and with the same pinned runtime. A fake data service stands in for the gateway, and every outgoing fetch is mocked.
import { memoryBackend } from '@astondb/contract/testing'
import { startWorker, type TestWorker } from '@astondb/executor/testing'
import c from '@leave/contract'
import { afterAll, beforeAll, expect, test } from 'vitest'
let app: TestWorker<typeof c>
beforeAll(async () => { app = await startWorker(c, { app: '.' }) }, 60_000)
afterAll(() => app.stop())
test('a manager approves a request', async () => {
const backend = memoryBackend({
request: [{ id: 1, author: 'jane@acme.example', state: 'new' }],
})
const r = await app.invoke('review', {
trigger: { source: 'api', user: { id: 2, email: 'john@acme.example' } },
body: { id: 1, approve: true },
user: { email: 'john@acme.example', name: 'John', roles: ['manager'] },
backend,
})
expect(r).toEqual({ ok: true, state: 'approved' })
expect(backend.events).toEqual([{ table: 'request', id: 1, operation: 'update' }])
})
A refusal is tested like any other outcome: invoke throws the JobError itself, so the test asserts the status and the sentence the caller would see — await expect(app.invoke('review', …)).rejects.toMatchObject({ status: 409 }).
| The handler uses | In the test |
|---|---|
env.RECORDS, env.FILES, env.EVENTS | memoryBackend(), or PGlite |
env.DB | await pgliteBackend(c, { migrations }): PostgreSQL in the test process, with the app's migrations |
env.SECRETS, env.OAUTH | secrets and oauth passed to invoke, with the contract's names; another name is a type error |
fetch | mockFetch(…); an unmocked call fails the test |
env.APPS: other apps, $view, $idp | mockApps({ call, fetch }) passed as apps; without it every call fails. A run started by another app still gets 403, and a call into the app itself 400, as in production |
env.ASYNC | the same mockApps: it records the call and returns the id of the wait, or refuses with 429 when the test fills the budget. A continuation is tested by invoking it with trigger.source: 'continue' and a body of your own |
| a command | commandRows(result, backend) returns the rows it would export |
Unit tests do not cover what the gateway enforces: who may call, operations and their check, the app's database role (PGlite has no roles), the exact CSV and Excel bytes, event chains, time limits, the queue, and permits: a mocked fetch or app call succeeds whether the admin has permitted it or not. Verify those on a test gateway after deploying.
19Rules of thumb
- Check the input first.
if (!body) returnat the top of every web job, because the same code can also run without input. - Write as if the job will run twice.Use
ifMatchfor state changes andenv.DB.batchfor writes that belong together. - Enforce row-level rules in code.
api.ownersays who may call the job, not which rows they may touch. - Trust no file id from the input.Check that the file belongs to the caller before passing it on.
- Re-read the row in event jobs.The world may have moved while the run waited in the queue.
- Chain through events, async calls or flows.A job cannot call another job of its own app, and writes through
envdo not emit events by themselves. An answer that takes minutes comes back fromenv.ASYNCin a later run, never from waiting in this one. - Expect a 403 from beyond the box.Every host and every other app needs a permit the admin may not have given yet, or may take back. Handle the refusal instead of crashing.
- Know whom you run for.Calls into other apps go as
run.user. From a schedule, an event or a flow step there is no person, and onlyasAppjobs and views are reachable. - Keep no state in module variables.The worker restarts with every deployment of the app and whenever a run hits the time limit.
- Remember it is workerd, not Node.Web APIs work;
node:*modules come without guarantees; native addons, the disk and child processes do not exist. - Log with
console.There is no other logger. The platform never logs a secret, but it cannot stop your code from doing so: keep secrets and tokens out of log lines.