Canica

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))
    }),
  },
})

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
})

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
    }),
  }),
})

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)
})

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?).