Back end
The back end
Back end
back-end.md

The back end

Examplea whole program
shape Line
sku: string
qty: number
shape Quote
lines: number
total: number
state lines: Line[] = [{sku: "door", qty: 2}, {sku: "pull", qty: 4}]
state quote: Quote? = none
// Only the back end uses this, so it is not in the page at all.
fn secretPrice(sku: string): number = sku == "door" ? 4175 : (sku == "pull" ? 650 : 0)
server fn price(order: Line[]): Quote
let total = 0
for l in order
if secretPrice(l.sku) == 0 fail(`no such thing as a ${l.sku}`)?
total += secretPrice(l.sku) * l.qty
return {lines: order.length, total}
action ask
quote = price(lines)?
column gap=8 padding=16
button "Quote" press=ask disabled=pending(ask)
if quote
text `${quote.lines} lines, ${quote.total} cents`
if failed(ask)
text (failure(ask) ?? "") color=danger

Mental model#

server fn#

What a server fn can use#

Snapshots#

Signing in#

Examplea whole program
shape Order
item: string
state who = "nobody"
state email = ""
state password = ""
state receipt = ""
server fn pay(o: Order): string requires signedIn
let u = auth.me()?
return `paid for ${o.item} by ${u?.email ?? "?"}`
action join
let u = auth.signUp(email, password)?
who = u.email
action enter
let u = auth.signIn(email, password)?
who = u.email
action leave
auth.signOut()?
who = "nobody"
action buy
receipt = pay({item: "door"}) else err => `refused: ${err}`
task whoAmI
let u = auth.me() else none
who = u?.email ?? "nobody"
column gap=8 padding=16 max-width=320
input value=email placeholder="Email" type=email
input value=password placeholder="Password" type=password
row gap=8
button "Sign up" press=join
button "Sign in" press=enter
button "Sign out" press=leave
text `Signed in: ${who}`
text (failure(join) ?? failure(enter) ?? "") color=danger
button "Buy" press=buy
text receipt

Passwords from the program's own code#

Examplea whole program
// A link that was sent: the token's hash (never the token), whose it is, until
// when it is good, whether it was used. No rules, so no page can reach it.
model Reset
hash: string key
user: string
until: time
used: bool = false
// This app's own row about a person; `admin` is set by whoever runs the app.
model Staff
id: id = me
admin: bool = false
read if id == me
add if me != none
fn mail(to: string, token: string)
net.send("POST", env("MAIL_URL"), {headers: {authorization: `Bearer ${env("MAIL_KEY")}`}, body: {to, subject: "Your link", text: `${env("SITE")}/reset/${token}`}})?
// The same answer whether or not the address has an account: the page (and
// whoever is typing addresses into it) learns nothing. Anyone may ask, and
// one address is sent three links an hour at most.
server fn forgot(email: string): string requires anyone limit 3 per hour by email
let u = auth.find(email)?
if u != none
let token = crypto.random(32)
Reset.add({hash: crypto.hash(token)?, user: u.id, until: Date.now() + 900000})?
detach mail(u.email, token)
return "If that address has an account, a link is on its way."
// The token is the check: good once, for a quarter of an hour. Spending it
// and setting the password are one (`atomic`), so a password that is refused
// leaves the link good.
server fn reset(token: string, password: string): string requires anyone limit 10 per minute by ip
let hash = crypto.hash(token)?
let email = ""
atomic
if Reset.setAll({hash, used: false, until: after(Date.now())}, {used: true})? != 1
fail("That link is no longer good.")?
let link = Reset.get(hash)?
auth.setPassword(link?.user ?? "", password)?
email = (auth.signInAs(link?.user ?? "")?).email
return email
// An admin sets someone a temporary password. The check is this app's own row.
server fn setTemporary(email: string, password: string): string requires signedIn
let me = Staff.get((auth.me()?)?.id ?? "")?
if me?.admin != true
fail("Only an admin does that.")?
let u = auth.find(email)?
auth.setPassword(u?.id ?? "", password)?
return "set"
state email = ""
state password = ""
state said = ""
action ask
said = forgot(email)?
action finish(token: string)
said = `Signed in as ${reset(token, password)?}.`
go("/")
column gap=8 padding=16 max-width=320
route "/"
input value=email type=email placeholder="Email"
button "Send me a link" press=ask
route "/reset/:token"
input value=password type=password placeholder="A new password"
button "Set it" press=finish(token)
text (failure(ask) ?? failure(finish) ?? said)

Accounts made by the program's own code#

Examplea whole program
// An invitation: an account is made for the address, with no password, and a link is
// sent there. Opening the link shows the address is theirs, and signs them in.
model Invite
hash: string key
user: string
until: time
used: bool = false
rule owner = exists(Staff, {who: me, owner: true})
model Staff
who: id unique
owner: bool = false
read if who == me
server fn invite(email: string): string requires owner limit 20 per hour
let made = auth.create(email)?
let token = crypto.random(32)
Invite.add({hash: crypto.hash(token)?, user: made.id, until: now() + 7 * 86400000})?
net.send("POST", env("MAIL_URL"), {body: {to: made.email, subject: "You are invited", text: `${env("SITE")}/#/join/${token}`}})?
return made.email
server fn join(token: string): string requires anyone limit 10 per minute by ip
let hash = crypto.hash(token)?
if Invite.setAll({hash, used: false, until: after(now())}, {used: true})? != 1
fail("That invitation is no longer good.")?
let user = (Invite.get(hash)?)?.user ?? ""
// (They opened a link that was mailed to the address: it is theirs.)
auth.setVerified(user)?
return (auth.signInAs(user)?).email
state email = ""
state said = ""
action send
said = `Invited ${invite(email)?}.`
action accept(token: string)
said = `Welcome, ${join(token)?}.`
go("/")
column gap=8 padding=16 max-width=320
route "/"
input value=email type=email placeholder="Whom to invite"
button "Invite" press=send
route "/join/:token"
button "Join" press=accept(token)
text (failure(send) ?? failure(accept) ?? said)

A sign-in of the program's own#

Examplea whole program
// How an account is found and checked at sign-in: by an id its holder's own
// secrets give, with the public half of a key those secrets give too. No
// rules, so no page reads it.
model Login
loginId: string key
user: string
key: string
// A challenge handed out: for which sign-in id, until when, whether spent.
model Challenge
hash: string key
loginId: string
until: time
used: bool = false
model Note
text: string
owner: id = me
read, add if owner == me
// A public key that is nobody's, for a try at an id nobody has.
fn decoy(): string = "T1PNoYwrqgwDVLtfmj7L5IEf1fFYDSNLUuRJ4vWNJnk"
server fn signUp(loginId: string, key: string): string requires anyone limit 5 per hour by ip
if Login.get(loginId)? != none
fail("that sign-in id is taken")?
let made = auth.create()?
Login.add({loginId, user: made.id, key})?
auth.signInAs(made.id)?
return made.id
// The same answer whether or not anyone has the id.
server fn begin(loginId: string): string requires anyone limit 30 per minute by ip
let challenge = crypto.random(32)
Challenge.add({hash: crypto.hash(challenge)?, loginId, until: now() + 120000})?
return challenge
server fn finish(loginId: string, challenge: string, signature: string): string requires anyone
auth.limit(loginId)?
let fresh = Challenge.setAll({hash: crypto.hash(challenge)?, loginId, used: false, until: after(now())}, {used: true})? == 1
let login = Login.get(loginId)?
let holds = crypto.verify({kty: "OKP", crv: "Ed25519", x: login?.key ?? decoy()}, `login ${challenge}`, signature, {alg: "EdDSA"}) else false
if !fresh || login == none || !holds
log.warn("sign-in failed", {loginId: loginId.slice(0, 4)})
fail("that sign-in did not hold")?
return (auth.signInAs(login?.user ?? "")?).id
text "Sign in"

Accounts several apps share#

Several apps, one database#

Examplea whole program
// shop/models.mote: the rows both apps keep, declared once.
model Customer
name: string
owner: id = me
read if owner == me || exists(Staff, {who: me})
add if me != none
model Staff
who: id unique
read if who == me
model Order
customer: Customer cascade
item: string
state: string = "new"
at: time = now
read if customer.owner == me || exists(Staff, {who: me})
add if customer.owner == me
change state if exists(Staff, {who: me})
model Price
item: string unique
cents: int
read anyone

What is shared, and what is each app's own#

A write in one app reaches the other's pages#

readonly: a model an app only reads#

Examplea whole program
app "Customer"
model Price
item: string unique
cents: int
read anyone
model Order
item: string
by: id = me
state: string = "new"
read if by == me
add if me != none
// This app reads the price list; the shop's app writes it.
readonly Price
// Of the back ends at one database, one sends the reminders.
server every 3600000 once
let waiting = Order.count({state: "new"})?
log(`${waiting} orders are waiting`)
live prices: Price[] = Price.find({}, {order: "item"}) else []
live mine: Order[] = Order.find({}, {order: "item"}) else []
action order(item: string)
Order.add({item})?
for p in prices key=p.id
row
text `${p.item}: ${p.cents / 100}`
button "Order" press=order(p.item)
for o in mine key=o.id
text `${o.item} is ${o.state}`

Starting up: whose schema#

Writes from two apps#

server every … once#

lock(name): one run at a time#

Examplea whole program
model Export
id: id
rows: number
at: time = now
server fn exportNow(): number requires signedIn
lock("nightly-export", {for: 600000})
let n = Export.count({})?
Export.add({rows: n})?
return n
return 0
action go
let n = exportNow() else err => (err.kind == "busy" ? -1 : 0)
log(n)
button "Export" press=go

Models in Postgres#

Settings#

What a write and a read are#

The schema in Postgres#

What another back end wrote#

Accounts and limits in Postgres#

Notifications and calls in Postgres#

Behind a transaction pooler#

Not as in SQLite#

What was checked#

Moving an app from SQLite to Postgres#

Stored files in an object store#

Files no row knows#

Containers with an ephemeral disk#

The key pushes are signed with#

A host paced, and a breaker#

Live values#

Examplea whole program
shape Msg
who: string
text: string
state room = "kitchen"
state draft = ""
state heard = ""
server live fn messages(room: string): Msg[]
let d = sql.open("chat")?
sql.run(d, "create table if not exists msg(room text, who text, text text)")?
let rows: Msg[] = sql.run(d, "select who, text from msg where room = ? order by rowid", [room])?
return rows
server fn say(room: string, who: string, text: string): number
let d = sql.open("chat")?
sql.run(d, "create table if not exists msg(room text, who text, text text)")?
sql.run(d, "insert into msg values (?, ?, ?)", [room, who, text])?
changed("messages", room)
emit("said", {who, room})
return 1
live msgs: Msg[] = messages(room) else []
on said(e: {who: string, room: string})
heard = `${e.who} spoke in ${e.room}`
action send
say(room, "me", draft)?
draft = ""
column gap=8 padding=16
row gap=8
for r in ["kitchen", "garage"]
button r press={room = r}
input value=draft submit=send
button "Send" press=send
for m in msgs
text `${m.who}: ${m.text}`
text heard color=dim

Is there a line: net.online#

Examplea whole program
state unsent: string[] = []
state draft = ""
state sent = 0
server live fn count(): number
return 7
server fn post(words: string): number
return words.length
live kept: number = count() else 0
action send
if !net.online
unsent.push(draft)
draft = ""
return
post(draft)?
sent += 1
draft = ""
action flush
for words in unsent
post(words)?
sent += 1
unsent = []
watch net.online
if net.online flush()
column gap=8 padding=16
if !net.online
text "No connection: what you write is kept and sent when it is back." color=danger
input value=draft
button "Send" press=send
text `${sent} sent, ${unsent.length} waiting, ${kept} kept`

Events#

Notifications#

Examplea whole program
// A direct message: pushed to the person's phones only, with what the page needs to act on it.
state heard = ""
server fn dm(to: string, text: string): number requires signedIn
let from = auth.me()?
let note = {title: "New message", body: text, url: `/#/dm/${from?.id ?? ""}`}
notify.send(to, note, {data: {why: "dm", from: from?.id ?? ""}, only: "phone", tag: "dm"})?
return 1
on notified(n: {id: number, title: string, body: string, url: string, data: {why: string, from: string}})
heard = `${n.data.why} from ${n.data.from}: ${n.body}`
// A notification was pressed, and this window was brought forward for it.
on notify.opened(n: {id: number, title: string, body: string, url: string, data: {why: string, from: string}?})
heard = `opened ${n.url}`
action allow
notify.enable()?
column gap=8 padding=16
if notify.allowed() == "default"
button "Tell me about new messages" press=allow
if notify.allowed() == "denied"
text "Notifications are turned off for this site in the browser." color=dim
text heard

What a device is#

Who can do what#

A push the app's own code opens#

Examplea whole program
app "Mail"
state note = ""
// The back end sends {data: {sealed}}: what it cannot read itself.
fn openNote(key: json, sealed: string): string
let all = bytes.base64(sealed)?
return crypto.aes.open(key, all.slice(0, 12), all.slice(12), {aad: "push"})?.text()
on push.received(p: {data: {sealed: string, from: string}})
let key = db.get("device-key")?
let text = openNote(key, p.data.sealed)?
let buttons = [{id: "archive", title: "Archive"}, {id: "reply", title: "Reply"}]
notify.show("New message", text, {actions: buttons, data: {from: p.data.from}, tag: p.data.from})?
// A press on it, or on one of its buttons (`n.action`: "archive", "reply", or "" for the notification).
on notify.opened(n: {id: number, title: string, body: string, url: string, data: {from: string}?, action: string})
note = `${n.action == "" ? "opened" : n.action}: ${n.body}`
text note

Routes#

Examplea whole program
// Another service posts here when something happens; the token in the path
// says which channel it is for, and is the only check there is.
model Hook
token: string key
channel: string
model Post
channel: string
text: string
at: time = now
read anyone
server fn hookFor(channel: string): string requires signedIn
return Hook.add({token: crypto.random(16), channel})?.token
server route POST "/hooks/:token"(req)
let hook = Hook.get(req.params.token)?
if hook == none
return {status: 404, text: "no such hook"}
let body = req.json()?
Post.add({channel: hook.channel, text: `${body.text}`})?
return {status: 201, json: {ok: true}}
// A feed anyone may read, as plain text.
server route GET "/feed/:channel"(req)
let posts = Post.find({channel: req.params.channel}, {order: "at desc", limit: 20})?
return {text: posts.map(p => p.text).join("\n"), headers: {"cache-control": "max-age=60"}}
live posts = Post.find({channel: "den"}, {order: "at"}) else []
for p in posts key=p.id
text p.text

How much may be sent: body=#

Examplea whole program
model Block
path: string key
data: bytes
server route PUT "/blocks/:path"(req) requires anyone limit 600 per minute by ip body=4096
let data = req.bytes()?
Block.put({path: req.params.path, data})?
return {status: 201}
server fn note(words: string): number requires anyone body=2000
return words.length
text "Blocks"

HEAD#

Examplea whole program
model Block
path: string key
data: bytes
server route GET "/blocks/:path"(req) requires anyone
let block = Block.get(req.params.path)?
if block == none
return {status: 404, text: "not found"}
return {bytes: block.data}
text "Blocks"

Other origins: cors=#

Examplea whole program
model Block
path: string key
data: bytes
server route GET "/v1/:path"(req) requires anyone cors="*"
let block = Block.get(req.params.path)?
return block == none ? {status: 404} : {bytes: block.data}
server route PUT "/v1/:path"(req) requires anyone limit 60 per minute by ip cors={origins: setting.list("APP_ORIGINS"), headers: ["content-type", "x-proof"], maxAge: 86400}
Block.add({path: req.params.path, data: req.bytes()?})?
return {status: 201}
text "A store"

Answers that go as they are made#

Events out of a route#

Examplea whole program
server route POST "/api/words"(req) requires anyone limit 30 per minute by ip
let b = req.json()?
let words = `${b.text ?? ""}`.split(" ")
for word in words
if !req.event("delta", word)
return
time.sleep(50)
req.event("done", {words: words.length})
text "A stream for whoever asks"
Examplea whole program
model Note
text: string
at: time = now
index at
server route GET "/api/notes"(req) requires anyone
let sent = Number(req.lastEventId) || 0
while !req.closed()
for n in Note.find({at: after(sent)}, {order: "at", limit: 100})?
req.event("note", {text: n.text}, `${n.at}`)
sent = n.at
time.sleep(1000)
text "Notes, as they are written"

A body in pieces#

Examplea whole program
model Order
total: number
at: time = now
server route GET "/api/orders.ndjson"(req) requires signedIn
req.head({headers: {"content-type": "application/x-ndjson"}})
let last = 0
while true
let page = Order.find({at: after(last)}, {order: "at", limit: 500})?
if page.length == 0 || !req.write(page.map(o => JSON.stringify({total: o.total, at: o.at}) + "\n").join(""))
return
last = page[page.length - 1].at
text "Orders, as lines of JSON"

A net.stream passed on#

Examplea whole program
server route POST "/api/speak"(req) requires signedIn limit 20 per minute
let b = req.json()?
let s = net.stream("POST", "https://api.example.com/v1/speech", {auth: {bearer: secret("SPEECH_KEY")}, body: {text: `${b.text ?? ""}`}, timeout: 30000})?
if !s.ok
return {status: 502, json: {error: `the speech service said ${s.status}`}}
return {stream: s, headers: {"cache-control": "no-store"}}
text "Speech, passed on"

A file with Range#

Examplea whole program
server route GET "/media/:name"(req) requires signedIn
return {file: `media/${req.params.name}`, headers: {"cache-control": "private, max-age=3600"}}
text "Media"

Webhooks#

Examplea whole program
model Order
id: string key
paid: number = 0
job fn fulfil(order: string, amount: number) retries=5
Order.set(order, {paid: amount})?
server route POST "/stripe/webhook"(req) requires anyone limit 600 per minute by ip
let event = webhook.check(req, "stripe", secret("STRIPE_WEBHOOK_SECRET"))?
webhook.once(`${event.id}`)
if event.type == "checkout.session.completed"
fulfil(`${event.data.object.client_reference_id}`, Number(event.data.object.amount_total))
return {status: 200, json: {received: true}}
text "A shop"

DNS records#

Examplea whole program
model Domain
name: string key
token: string
owner: string
verified: bool = false
why: string = ""
read if owner == me
fn domainTarget(): string = "custom.myapp.example"
// What is wrong with a domain's records, or "" when they are right.
fn domainWrong(name: string, token: string): string
let points = net.lookup(name, "CNAME", {timeout: 3000})?
if !points.includes(domainTarget())
return `${name} is to be a CNAME of ${domainTarget()}`
let said = net.lookup(`_myapp.${name}`, "TXT", {timeout: 3000})?
if !said.includes(`myapp-verify=${token}`)
return `_myapp.${name} is to have a TXT record myapp-verify=${token}`
return ""
server fn domainAdd(name: string): Domain requires signedIn
let d = Domain.add({name: name.toLowerCase(), token: crypto.random(16), owner: auth.me()?.id ?? ""})?
domainLook(d.name, 0)
return d
// Looked at again and again (a minute, then longer), for a day; "offline" is tried again too.
job fn domainLook(name: string, turn: number) retries=3
let d = Domain.get(name)?
if d == none || d.verified return
let wrong = domainWrong(d.name, d.token)?
Domain.set(d.name, {verified: wrong == "", why: wrong})?
if wrong != "" && turn < 40
domainLook.in(Math.min(3600000, 60000 * Math.pow(2, Math.min(turn, 6))), name, turn + 1)
live mine = Domain.find({}) else []
for d in mine key=d.name
row gap=8
text d.name
text (d.verified ? "verified" : d.why) color=dim

Sending mail#

Examplea whole program
model Invite
code: string key
email: string
from: id = me
until: time
read if from == me
// One place that knows the mail service. What it is given is the service's
// own JSON; its address and its key are the back end's surroundings, never
// the page's.
fn mail(to: string, subject: string, text: string): string
let r = net.send("POST", `${env("MAIL_URL")}/messages`, {headers: {authorization: `Bearer ${env("MAIL_KEY")}`}, body: {from: env("MAIL_FROM"), to, subject, text}, timeout: 10000}) else none
if r?.ok != true
fail(`the mail was not sent (${r?.status ?? "the mail service did not answer"})`)?
return `${r?.json.id}`
server fn invite(email: string): string requires signedIn
let me = auth.me()?
if !email.includes("@")
fail("that is not an address")?
let code = crypto.random(16)
Invite.add({code, email, until: now() + 7 * 24 * 3600000})?
mail(email, "You are invited", `${me?.email ?? "Someone"} invites you: ${env("SITE")}/#/join/${code}`)?
return "sent"
state email = ""
state said = ""
action send
said = invite(email)?
email = ""
column gap=8 padding=16 max-width=320
input value=email type=email placeholder="Their address" submit=send
button "Invite" press=send disabled=pending(send)
text (failure(send) ?? said)

Other programs#

Connections of its own#

Examplea whole program
// A line-based protocol of a made-up service: a greeting, a command, an answer of a length.
server fn price(sku: string): number
let c = tcp.open(env("QUOTES_HOST"), 7070, {tls: true, timeout: 5000})?
let hello = c.line()?
if hello == none || !hello.startsWith("QUOTES") fail("that is not the quote service")?
c.write(`PRICE ${sku}\r\n`)?
let size = c.read(4)?.read(0, "u32be")
let body = c.read(size)?.text()
c.close()
return Number(body)
action ask
log(price("oak-3")?)
button "Ask" press=ask

Pools#

Accepting connections: server listen#

Examplea whole program
// A little line protocol: a greeting, then one command a line, each answered with a code.
fn session(c: socket)
while true
let l = c.line(none, 512) else err => `!${err.kind}`
if l == "!toobig"
c.write("500 that line is too long\r\n")?
continue
if l == "!stopping"
c.write("421 going away\r\n")?
return
if l == none || l.startsWith("!")
return
if l == "STARTTLS"
c.write("220 go ahead\r\n")?
c.startTls()?
else if l == "QUIT"
c.write("221 bye\r\n")?
return
else
c.write(`250 ${c.remote.address} said ${l}\r\n`)?
server listen lines(c) port=env("LINES_PORT") cert=env("TLS_CERT") key=env("TLS_KEY") timeout=60000 refuse="421 too busy\r\n" limit 20 per minute by ip
c.write("220 ready\r\n")?
session(c)?

A WebSocket from the back end#

Examplea whole program
// Prices as a service streams them: told what to send, then each message as it comes.
fn follow(symbol: string)
let w = ws.open("wss://stream.example/v1", {headers: {authorization: `Bearer ${secret("STREAM_KEY")}`}, reconnect: true})?
w.send(JSON.stringify({subscribe: symbol}))?
while true
let m = w.next(60000) else err => none
if m == none
if w.state == "closed" break
w.ping()?
continue
if m.reopened
w.send(JSON.stringify({subscribe: symbol}))?
continue
emit("price", JSON.parse(m.text))
server start
detach follow("OAK")
state last = ""
on price(p: json)
last = `${p}`
text last

Folders#

Work of its own#

Examplea whole program
// Runs the tests of a checkout, and tells every page each line as it is printed.
model Run
state: string = "running"
output: string = ""
at: time = now
read anyone
state heard = ""
live runs = Run.find({}, {order: "at desc", limit: 5}) else []
fn work(id: string)
let repo = fs.folder(env("REPO"))?
let job = proc.start(["bun", "test"], {cwd: repo.path, timeout: 600000})?
while true
let line = job.line()
if line == none
break
emit("line", line)
let done = job.done()?
Run.set(id, {state: done.code == 0 ? "passed" : "failed", output: done.out + done.err})?
// Answers at once; the work goes on.
server fn test(): string requires signedIn
let run = Run.add({})?
detach work(run.id)
return run.id
// The back end was stopped with runs under way: each is begun again.
server start
for run in Run.find({state: "running"})?
detach work(run.id)
// Every hour, runs older than a week go.
server every 3600000
Run.del({at: before(now() - 7 * 24 * 3600000)})?
on line(text: string)
heard = text
action go
test()?
column gap=8 padding=16
button "Run the tests" press=go
text heard color=dim
for r in runs
text `${time.clock(r.at)}: ${r.state}`

At a time of day#

Examplea whole program
model Order
item: string
state: string = "new"
at: time = now
read anyone
model Report
day: string key
orders: int
// Each night at three (UTC, unless a zone is said): yesterday's orders, counted.
server at "03:00"
let from = time.startOf(now() - 86400000, "day", {zone: "UTC"})
Report.add({day: time.stamp(from, "UTC").slice(0, 10), orders: Order.count({at: between(from, from + 86400000)})?})?
// Monday and Thursday at half past six in the evening, by New York's clock.
server at "mon,thu 18:30" zone="America/New_York"
log.info("the week's list goes out")
live orders = Order.find({}, {order: "at"}) else []
for o in orders key=o.id
text o.item
Examplea whole program
// A digest at 09:00 in each person's own zone, every day.
model Member
id: id = me
name: string
zone: string = "UTC"
// When their next digest is due (0: not asked for).
due: time = 0
read anyone
add if me != none
change name, zone, due if id == me
state said = ""
// The page says which zone its person is in, and the first digest is set.
server fn wantDigest(zone: string): number requires signedIn
let me = auth.me()?
let due = time.next({hour: 9, minute: 0}, zone, now())
Member.set(me?.id ?? "", {zone, due})?
return due
// Each minute: whoever is due is sent theirs, and their next is set.
server every 60000
for m in Member.find({due: between(1, now())})?
notify.send(m.id, {title: "Your morning digest", body: `Good morning, ${m.name}`, url: "/#/digest"}, {tag: "digest"})?
Member.set(m.id, {due: time.next({hour: 9, minute: 0}, m.zone, now())})?
action want
let due = wantDigest(time.zone())?
said = `The first comes ${time.words(due)}, at ${time.clock(due)}`
column gap=8 padding=16
button "Send me a digest every morning" press=want
text said

Later: job fn#

Examplea whole program
model Person
id: id = me
name: string
welcomed: bool = false
read anyone
add if me != none
model Order
item: string
by: id = me
state: string = "new"
read if by == me
add if me != none
// Runs later, and again if it fails: 1 s, 4 s, 16 s on, three times at most.
job fn welcome(who: id) retries=3
let p = Person.get(who)?
if p == none || p.welcomed return
let said = net.send("POST", env("MAIL_URL"), {body: {to: who, text: `Welcome, ${p.name}`}})?
if said.status != 200 fail(`the mail service said ${said.status}`)?
Person.set(who, {welcomed: true})?
// One sweep of an order at a time: asked for twice while it waits, it is queued once.
job fn settle(order: id) unique timeout=60000
Order.set(order, {state: "settled"})?
// Queued by the back end's own code, wherever a row is added from.
server after Person.add(p)
welcome(p.id)
// The order and its job are one: kept together, or neither.
server fn place(item: string): string requires signedIn
let id = ""
atomic
let o = Order.add({item})?
id = settle.in(60000, o.id)
return id
server fn unplace(job: string): bool requires signedIn
return jobs.cancel(job)?
// A job that was given up on.
server on jobFailed(j)
log.error("gave up", {job: j.name, tries: j.tries, why: j.words})
state name = ""
action join
Person.add({name})?
action buy
place("door")?
column gap=8 padding=16
input value=name placeholder="Your name"
button "Join" press=join
button "Buy a door" press=buy

Nothing but the data waits inside atomic#

Another back end#

Examplea whole program
shape Cabinet
name: string
width: number
shape Kitchen
id: string
cabinets: Cabinet[]
server fn receiveKitchen(pack: Kitchen): string requires peer
if pack.cabinets.length == 0 fail("A kitchen with no cabinets is not sent to the shop.")?
return `job-${pack.id}`
text "The shop"
Examplea whole program
shape Cabinet
name: string
width: number
shape Kitchen
id: string
cabinets: Cabinet[]
extern server fn receiveKitchen(pack: Kitchen): string at env("SHOP_URL")
server fn send(k: Kitchen): string requires signedIn
return receiveKitchen(k)?
state job = ""
action sendIt
job = send({id: "k1", cabinets: [{name: "B1", width: 600}]})?
button "Send to the shop" press=sendIt
text `${job} ${failure(sendIt) ?? ""}`
Examplea whole program
shape Kitchen
id: string
extern server fn receiveKitchen(pack: Kitchen): string at env("SHOP_URL") timeout=5000
// Kept to send again when the shop cannot be reached; dropped when the shop said no.
server fn send(k: Kitchen): string
let job = receiveKitchen(k) else err => (err.kind == "offline" || err.kind == "timeout" ? "later" : err.kind == "fault" ? `broken (id ${err.id})` : "")
if job == "" fail("The shop did not take it.", {kind: "refused-by-shop"})?
return job
action go
send({id: "k1"})?
button "Send" press=go
text (failure(go) ?? "")

Describing the back end#

A page drawn ahead#

Examplea whole program
app "Shop" routes=paths render=ahead
shape Item
id: number
name: string
server fn items(): Item[] = [{id: 1, name: "Oak shelf"}, {id: 2, name: "Pine box"}]
resource all: Item[] = items() else []
column gap=8 padding=16
route "/"
h1 "Shop"
for it in all key=it.id
link it.name href=(`/item/${it.id}`)
route "/item/:id"
text (all.find(x => `${x.id}` == id)?.name ?? "No such thing")

Logs#

Examplea whole program
shape Order
id: string
total: number
server fn place(o: Order): string
log.info("order placed", {order: o.id, total: o.total})
if o.total > 10000 log.warn("a large order", {order: o.id})
let key = secret("PAY_KEY")
log.debug("asking the payment service", {key})
return o.id
action buy
place({id: uid(), total: 12})?
button "Buy" press=buy

Where a fault was written#

Examplea whole program
server fn place(n: number): number
let rows: json = none
return total(rows) + n
fn total(rows: json): number
return rows.count
server on failure(f)
log.warn("noted", {at: f.at ?? "", stack: f.stack})
state said = ""
action go
said = `${place(1) else err => err.kind}`
fn broken(): number
let nothing: json = none
return nothing.y
action bad
said = `${broken()}`
on failure(f)
said = `${f.words} (${f.at ?? "somewhere"})`
column gap=8 padding=16
button "Place" press=go
button "Break" press=bad
text said

The call's id#

A call is answered once#

Examplea whole program
app "Till" timeout=20000
server fn charge(cents: number): string
return `charged ${cents}`
state said = ""
action pay
said = charge(1200) else err => `${err.kind}: ${err}`
column gap=8 padding=16
button "Pay" press=pay disabled=pending(pay)
text said

When something fails#

Examplea whole program
state note = ""
server fn reserve(sku: string, n: number): number
if n > 3 fail("out of stock", {kind: "stock", data: {sku, left: 3}})?
return n
action take
note = ""
let got = reserve("lamp", 5) else err => (err.kind == "stock" ? -1 : 0)
if got < 0 note = "Only a few left."
action buy
reserve("lamp", 5)?
on failure(f)
if f.kind == "signin" go("/signin")
else toast(f.words)
column gap=8 padding=16
button "Take" press=take
button "Buy" press=buy
text note
text `${failure(buy) ?? ""} ${failure(buy)?.kind ?? ""} ${failure(buy)?.data?.left ?? ""}`

A create that loses: taken#

Examplea whole program
model Account
handle: string unique
email: string
fn made(handle: string, email: string): string
Account.add({handle, email})?
return "made"
server route PUT "/accounts/:handle"(req) requires anyone body=256
let row = Account.add({handle: req.params.handle, email: req.text()?}) else err => (err.kind == "taken" ? none : err?)
return row != none ? {status: 201} : {status: 409, text: "taken"}
server fn claim(handle: string): string requires anyone
return made(handle, "") else err => (err.kind == "taken" ? `${err.data.fields.join(", ")} is someone else's` : "")
text "Accounts"

The words of each kind#

Examplea whole program
state note = ""
server fn save(text: string): string
return "Saved."
action keep
note = save("x") else err => (err.kind == "offline" || err.kind == "timeout" ? "No connection. Try again." : `${err}`)
button "Save" press=keep
text note
Examplea whole program
model Fault
where: string
call: string
words: string
ref: string
at: time = now
server on failure(f)
Fault.add({where: f.where, call: f.call ?? "", words: f.words, ref: f.id})?
if env("ALERT_URL") != ""
net.post(env("ALERT_URL"), {text: `${f.call ?? f.where}: ${f.words} (id ${f.id})`})?
server fn risky(n: number): number
let rows: json = none
return rows.count + n
action go
risky(1)?
button "Go" press=go
text (failure(go) ?? "")

Requests to other machines have a limit#

Health and stopping#

Examplea whole program
state said = ""
server fn work(job: string): string
fs.append("jobs.txt", job + "\n")?
return job
server every 60000
fs.append("beat.txt", `${now()}\n`)?
// Run once, when the back end is asked to stop: after the calls in flight, before the databases close.
server stop
fs.append("jobs.txt", "stopped cleanly\n")?
log.info("goodbye")
action go
said = work("door")?
button "Go" press=go
text said

What the back end is#

Examplea whole program
rule staff = exists(Staff, {who: me})
model Staff
who: id unique
server fn health(): string requires staff
let info = app.info()?
let unset = info.settings.filter(s => !s.set).map(s => s.name)
return `${info.name} ${info.build}, up since ${time.stamp(info.started, "UTC")}; ${info.data.length} databases; not set: ${unset.join(", ")}; mail from ${env("MAIL_FROM")}`
state said = ""
action ask
said = health()?
button "Health" press=ask
text said

Guarding a call#

Rules#

Examplea whole program
rule member(channel: id) = exists(Member, {channel: channel, who: me})
rule admin = exists(Member, {who: me, role: "admin"})
model Member
channel: string
who: id = me
role: string = "member"
read if who == me || admin
add if me != none
model Message
channel: string
from: id = me
text: string
read, add if member(channel)
remove if from == me || admin
shape Post
channel: string
text: string
// Only an admin who is in the channel empties it.
server fn purge(channel: id): number requires admin && member(channel)
return Message.del({channel})?
server fn post(p: Post): string requires member(p.channel)
return (Message.as(me).add({channel: p.channel, text: p.text})?).id
// Open to anyone who reaches the back end, and says so.
server fn status(): string requires anyone
return "up"
server live fn count(channel: id): number requires member(channel)
return Message.count({channel})?
server route GET "/export/:channel"(req) requires member(channel)
return {text: (Message.find({channel: req.params.channel})?).map(m => m.text).join("\n")}
state channel = "den"
state said = ""
live messages: Message[] = Message.find({channel}) else []
action empty
said = `${purge(channel) else err => (err.kind == "refused" ? "Only an admin does that." : err)}`
column gap=8 padding=16
for m in messages key=m.id
text m.text
button "Empty the channel" press=empty
text said

A rule that reads a setting#

Examplea whole program
rule admin = me.email in setting.list("SHOP_ADMINS")
rule open = setting("SHOP_MODE") == "open"
model Note
text: string
owner: id = me
read if owner == me || admin
add if me != none
change, remove if admin
server fn wipe(): number requires admin
return Note.del({})?
server fn hours(): string requires open || admin
return "9 to 5"
text "Notes"

Limits#

Examplea whole program
state said = ""
state email = ""
// By who is signed in; for someone who is not, by their address.
server fn search(q: string): string requires anyone limit 30 per minute
return `nothing for ${q}`
// By what it is for: one address is sent two links an hour, whoever asks.
server fn sendLink(to: string): string requires anyone limit 2 per hour by to
return "If that address has an account, a link is on its way."
server route POST "/hooks/:token"(req) limit 60 per minute by token
return {json: {ok: true}}
action ask
said = sendLink(email) else err => (err.kind == "limited" ? `Try again in ${err.data.retryAfter} seconds.` : err)
column gap=8 padding=16
input value=email type=email
button "Send me a link" press=ask
text said

The open line, origins and frames#

Secrets#

Examplea whole program
state said = ""
server fn pay(order: string, cents: number): string requires signedIn
let key = secret("PAY_KEY")
log.info("paying", {order, key})
let answer = net.send("POST", env("PAY_URL"), {headers: {authorization: `Bearer ${key}`}, body: {order, cents}})?
return answer.ok ? "paid" : "refused"
action buy
said = pay("o1", 1200)?
button "Pay" press=buy
text `${said}${failure(buy) ?? ""}`

Acting as someone#

Examplea whole program
rule support = exists(Staff, {who: me, support: true})
model Staff
who: id unique
support: bool = false
read if who == me
model Note
by: id = me
text: string
read if by == me
add if me != none
// The program's own record of who looked at whose account. No rule: no page reads it.
model Looked
by: id
at: id
toWrite: bool
when: time = now
// Who may is this fn's `requires`: without one it does not compile.
server fn lookAs(email: string): string requires support
let them = auth.find(email)?
if them == none return fail("There is no such account.")?
Looked.add({by: (auth.me()?)?.id ?? "", at: them.id, toWrite: false})?
return (auth.as(them.id)?).email
server fn whoIsHere(): string requires signedIn
let real = auth.actor()?
return real == none ? "nobody is acting" : `${real.email} is acting`
state email = ""
state said = ""
live notes: Note[] = Note.find({}) else []
action look
said = lookAs(email)?
column gap=8 padding=16
if auth.acting
text `You see what ${auth.acting?.as?.email ?? ""} sees${auth.acting?.look ? ", and change nothing" : ""}.`
button "Back to myself" press={auth.asEnd() else none}
else
input value=email type=email placeholder="A user's email"
button "See what they see" press=look
for n in notes key=n.id
text n.text
text (failure(look) ?? said)

Usage#

Examplea whole program
app "Shop" usage=on
model Seen
what: string
who: string = ""
at: time = now
// Every five seconds, and once more as the back end stops: what was gathered since.
server on usage(batch)
for e in batch
if e.kind == "track" || e.kind == "signup"
Seen.add({what: e.name, who: e.user ?? ""})?
server fn buy(sku: string): string
track("bought", {sku})
return sku
action go
buy("door")?
button "Buy" press=go

Who may do what#

Examplea whole program
model Member
id: id = me
name: string
read anyone
add if me != none
model Seat
room: string
who: Member = me
guest: bool = false
read if who == me
add if me != none
model Note
room: string
by: Member = me
text: string
read if exists(Seat, {room: room, who: me})
add if exists(Seat, {room: room, who: me, guest: false})
remove if exists(Seat, {room: room, who: me})
model Invite
room: string
code: string unique
read if exists(Seat, {room: room, who: me})
// Whoever holds an invitation's code is seated in its room.
server fn join(code: string): string
let i = Invite.one({code})?
if i == none return fail("that invitation is not valid")?
return Seat.as(me).add({room: i.room})?.room
state room = ""
state text = ""
live notes: Note[] = Note.find({room}) else []
action enter(code: string)
room = join(code)?
action say
Note.add({room, text})?
text = ""
column gap=8 padding=16
input value=text submit=say placeholder="A note"
for n in notes key=n.id
row gap=8
text n.text flex=1
button "×" press={Note.del(n.id) else 0}
button "Join" press=enter("den-4f2a")
text (failure(enter) ?? failure(say) ?? "") color=danger

What this lets a program do#

What ships where#

Running it#

The wire#

Pitfalls#

In the source#

On this pageMental modelserver fnWhat a server fn can useSnapshotsSigning inPasswords from the program's own codeAccounts made by the program's own codeA sign-in of the program's ownAccounts several apps shareSeveral apps, one databaseWhat is shared, and what is each app's ownA write in one app reaches the other's pagesreadonly: a model an app only readsStarting up: whose schemaWrites from two appsserver every … oncelock(name): one run at a timeModels in PostgresSettingsWhat a write and a read areThe schema in PostgresWhat another back end wroteAccounts and limits in PostgresNotifications and calls in PostgresBehind a transaction poolerNot as in SQLiteWhat was checkedMoving an app from SQLite to PostgresStored files in an object storeFiles no row knowsContainers with an ephemeral diskThe key pushes are signed withA host paced, and a breakerLive valuesIs there a line: net.onlineEventsNotificationsWhat a device isWho can do whatA push the app's own code opensRoutesHow much may be sent: body=HEADOther origins: cors=Answers that go as they are madeWebhooksDNS recordsSending mailOther programsConnections of its ownPoolsAccepting connections: server listenA WebSocket from the back endFoldersWork of its ownAt a time of dayLater: job fnNothing but the data waits inside atomicAnother back endDescribing the back endA page drawn aheadLogsWhere a fault was writtenThe call's idA call is answered onceWhen something failsA create that loses: takenThe words of each kindRequests to other machines have a limitHealth and stoppingWhat the back end isGuarding a callRulesLimitsThe open line, origins and framesSecretsActing as someoneUsageWho may do whatWhat this lets a program doWhat ships whereRunning itThe wirePitfallsIn the source
esc
1072 sections of 111 pages, ranked as you type.A heading's words count for more than what stands under it.
↑↓move
↵open
ranked by BM25, in the page