Server
import { schema, table, query, mutation, string, id, userId, TaggedError, Viewer, eq, desc } from "canica/server"
export const { app, Db, tables } = schema({
rooms: table({ name: string().trim().min(1).max(80) }).unique("by_name", ["name"]),
messages: table({ room: id("rooms").onDelete("cascade"), author: userId(), body: string().trim().min(1).max(2000) })
.index("by_room", ["room"]),
})
const { rooms, messages } = tables // Drizzle tables: id, createdAt, updatedAt + fields
export class NameTaken extends TaggedError("NameTaken")<{ readonly name: string }> {}
export default app({
queries: {
messages: query({ room: id("rooms") }, function* ({ room }) {
const db = yield* Db
yield* db.get(rooms, room) // fails with NotFound
const newest = yield* db.select().from(messages).where(eq(messages.room, room)).orderBy(desc(messages.createdAt)).limit(50)
return newest.reverse()
}),
},
mutations: {
createRoom: mutation({ name: string().trim().min(1).max(80) }, function* ({ name }) {
const db = yield* Db
const [taken] = yield* db.select({ id: rooms.id }).from(rooms).where(eq(rooms.name, name)).limit(1)
if (taken) return yield* new NameTaken({ name }) // check first: a unique violation is a bug
const [room] = yield* db.insert(rooms).values({ name }).returning()
return room!.id
}),
send: mutation({ room: id("rooms"), body: string().trim().min(1).max(2000) }, function* ({ room, body }) {
const db = yield* Db
yield* db.insert(messages).values({ room, author: (yield* Viewer).userId, body })
}),
},
// Mutations clients cannot call: crons, the scheduler, actions and `canica run <name>` can (as the system user).
internal: {
clearRoom: mutation({ room: id("rooms") }, function* ({ room }) {
const db = yield* Db
yield* db.delete(messages).where(eq(messages.room, room))
}),
},
})
- Handlers are generators (
yield*instead ofawait), synchronous, deterministic. Services:Db,Viewer({ userId, isGuest, isSignedIn, profile? }),Files(see Files), and in mutations onlyNow(epoch ms),Random(int,string(n),uuid),SchedulerandEmail(also in actions; see Email). The compiler rejects a query that writes or usesNow/Random. Don't annotate handler types. - Fail with typed errors (
return yield* new MyError()); they reach the client types. Throwing is a bug (rollback). - A mutation is one transaction; mutations run one at a time, so "check, then insert" is safe.
Actions call the network and use secrets; queries and mutations cannot. Not transactional, not live, no Db:
fetch outside, then save with a mutation, so pages see the result live.
import { apis } from "./apis.gen/index.ts" // see External APIs
export default app({
queries: { … }, mutations: { saveIssues: mutation({ repo: string(), titles: array(string()) }, function* … ) }, internal: { … },
apis,
// A function, so ctx.runQuery/runMutation are typed by the handlers above.
actions: (action) => ({
syncIssues: action({ owner: string(), repo: string() }, function* (ctx, { owner, repo }) {
const issues = yield* ctx.apis.github.issuesListForRepo({ owner, repo, state: "open" })
return yield* ctx.runMutation("saveIssues", { repo, titles: issues.map((i) => i.title) })
}),
quote: action(function* (ctx) {
const { quote } = yield* ctx.fetchJson("https://quotes.example/today", object({ quote: string() }))
return quote
}),
syncAll: action.internal(function* (ctx) { … }), // clients cannot call it; crons, the scheduler and actions can
}),
crons: { syncAll: { every: "15 minutes", run: "syncAll", args: {} } }, // a mutation or action, as the system user
})
ctx:viewer,now(),apis(below),fetchJson(url, field, init?)(decodes the JSON with a field or an Effect Schema;FetchFailedwithstatuson an HTTP error or a body that does not match),fetchText(url, init?)(the body as a string: HTML, CSV, text;FetchFailedwithstatuson an HTTP error),fetch(url, init)(the rawResponse, for what the others do not cover;FetchFailedwhen unreachable),secrets.NAME,runQuery/runMutation(internal ones too; each its own transaction, as the same user; their typed errors flow into the action's),runAction,scheduler. Neverfetch/Date.now()(lint; tests stub the network).- Secrets: production:
canica secrets set GITHUB_TOKEN(asks for the value; applies on the next deploy); dev:.env(CANICA_SECRET_GITHUB_TOKEN=…) or.canica/secrets(GITHUB_TOKEN=…), both gitignored. Never log or return them. - Later:
(yield* Scheduler).runAfter(ms, "name", args)in a mutation (saved with its writes: only if it commits),ctx.scheduler.runAfter(…)in an action. It runs a mutation or action (internal too) as the same user; name and args are typed likectx.runMutation; pending jobs survive restarts and deploys.
Endpoints answer HTTP from other servers: webhooks (Stripe, GitHub, a form service), a script, another app. They
live at https://<app>.canica.run/api/…; pages are never there (a src/routes/api/ route is refused).
import { cents, hmacSha256, sameSignature, string } from "canica/server"
export default app({
// A function, like actions: ctx is an action's, typed by the handlers above.
endpoints: (endpoint) => ({
paid: endpoint.post("/api/webhooks/paid", function* (ctx, request) {
const body = yield* request.text() // the raw body: the signature is computed over it
const expected = yield* hmacSha256(ctx.secrets.WEBHOOK_SECRET, body)
if (!sameSignature(`sha256=${expected}`, request.headers.get("x-signature"))) return new Response("Bad signature", { status: 401 })
const event = yield* request.json({ ref: string(), amount: cents() }) // checked like mutation args: 400 if not
yield* ctx.runMutation("recordPayment", event)
return { received: event.ref } // 200, as JSON
}),
order: endpoint.get("/api/orders/:id", function* (ctx, request) {
return yield* ctx.runQuery("orderById", { id: request.params.id }) // NotFound → 404
}),
}),
})
endpoint.get/post/put/patch/delete(path, handler). Paths start with/api/;:namesegments arerequest.params.name; a literal segment wins over a param (/api/orders/newbefore/api/orders/:id).request:method,url,params,query(URLSearchParams),headers, and the body (read once, at most 1 MB):text(),bytes(),json(fields)({ email: string() }or one field such asarray(object({ … }))).- Return a
Response(any status, headers, body), plain data (200 JSON) or nothing (204). Typed errors answer JSON{ error: { _tag, … } }:InvalidArgs400,NotFound404,LimitReached429, your own 422. A bug answers 500 (the message is incanica logs). No route for the path: 404; another method: 405 withAllow. - Anyone on the internet may call an endpoint, whatever
accesssays, and it runs as the system user (like a cron): check the caller yourself, with a signature (hmacSha256(secret, body, "hex" | "base64"), compared withsameSignature) or a token (sameSignature(request.headers.get("authorization"),Bearer ${ctx.secrets.API_TOKEN})). Their writes count against the app's daily limit. They are for servers: no cookies, no CORS. - Dev:
http://localhost:5173/api/…. Tests:await t.fetch("/api/webhooks/paid", { method: "POST", body, headers }), thenres.statusandawait res.json()(testApp(app, { secrets })for the signing secret).
External APIs: typed clients generated from OpenAPI documents, for actions.
// server/apis.ts
import { api, bearer, header, none, secret } from "canica/server"
export const github = api({
openapi: "https://raw.githubusercontent.com/github/rest-api-description/main/descriptions/api.github.com/api.github.com.json",
operations: ["issues/list-for-repo", "issues/create"], // operationIds (or tags: [...]); only what you use
auth: bearer(secret("GITHUB_TOKEN")), // or header("x-api-key", secret("NAME")), none (default)
// baseUrl: "https://github.example.com/api/v3", hosts: ["github.example.com"] (who gets the credential)
})
canica apisdownloads each document once (.canica/apis/,--refreshto download again), keeps those operations and what they reference, and writesserver/apis.gen/(commit it;canica dev,canica routes(npm run typecheck) andcanica deployregenerate it when a declaration changed). Passapistoapp({ apis }).yield* ctx.apis.github.issuesListForRepo({ owner, repo, state: "open" }): path, query and header parameters by name, the request body aspayload(issuesCreate({ owner, repo, payload: { title } })); the result is typed and checked against the spec. Errors: the statuses the spec declares (IssuesListForRepo404withstatusand a typedbody) andApiFailed(unreachable, an undeclared status, a response that does not match the spec). They reach the client's types like your own errors.- Canica adds the credential from the secret and only sends it to the API's host; your code never sees it.
- Tests:
testApp(app, { apis: { github: { issuesListForRepo: ({ repo }) => [{ number: 1, title: "Bug", … }] } } })(a value, or aResponsedecoded as the API's:() => Response.json({ message: "Not Found" }, { status: 404 })gives the typed error); operations without a stub go totestApp'sfetch.
Schema: a table is its fields, and the same fields validate mutation args and forms. string() (.trim() .lower() .upper() .min(n, msg?) .max(n) .pattern(re) .email()), number() (.int() .min .max),
boolean(), id("table") (.onDelete("cascade"), needs an index or unique starting with it), userId(), file() (an upload, see Files), literal("a", "b"),
day() ("YYYY-MM-DD"), cents() (an amount > 0; forms read "12.50" as 1250), array(f), object({…}).
Instants are number() (epoch ms, from Now). Then .optional() (reads as null) or .default(v). Messages show in forms and InvalidArgs.
A field added to a table with rows must be optional or have a default. A list you filter, join or cascade on is a
child table, not an array(id(…)).
Queries are Drizzle (db.select()…, insert, update, delete; conditions such as eq, and, inArray, desc
from canica/server), run with yield*. Canica adds db.get(t, id) (row or NotFound) and db.count(t, where?).
- Live queries re-run when a write touches what they read. A table filtered with
eq/inArray(joined withand) is watched by those values; read without one, it re-runs on any write to it. Filter every query by its scope (owner, room, poll). - Never set
id/createdAt/updatedAt. Order bycreatedAtfor insertion order. One select returns at most 10 000 rows. - Helpers (from
canica/fieldsinshared/, also incanica/serverandcanica/client):addDays daysBetween weekday startOfWeek lastDayson days,formatCents(cents, "EUR"),plural(n, "vote"),formatDate(ms),formatTime(ms, now).