defineLuna
Every option of defineLuna for a keyed or a stateless luna type, its hooks and crons, and the luna type it returns.
defineLuna turns a spec into a luna type, which you export from your lunas module so that it deploys.
import { defineLuna, t, table } from "luna";
export const List = defineLuna({
name: "List",
visibility: "public",
key: { id: t.string() },
schema: {
items: table({ id: t.id(), text: t.string() }),
},
handlers: (h) => ({
add: h({ args: { text: t.string() } }, (ctx, { text }) => {
ctx.db.items.insert({ text });
}),
all: h({ query: true }, (ctx) => ctx.db.items.find({ orderBy: "id" })),
}),
});
Reference
defineLuna(spec)
import { defineLuna } from "luna";
Takes a LunaSpec, or a StatelessSpec for a stateless type, and returns a Luna. It throws at once for a bad name, a bad key field or an option a stateless type cannot have.
LunaSpec
namestring
The luna type's name, used in every URL and call.
stringhandlers(h: HandlerFactory) => Record<string, Handler>
Returns the handlers, each made with h(spec, run). See Handler spec.
(h: HandlerFactory) => Record<string, Handler>key?Record<string, Ty>
The key fields that pick one luna. With none, the type has exactly one luna.
Record<string, Ty>{}visibility?"private" | "public"
Public types can be called with a publishable key. Private ones need a secret token.
"private" | "public""private"schema?Record<string, TableDef>
Each luna's tables, made with table().
Record<string, TableDef>{}hooks?object
Functions that run at points in a luna's life and on connections. See Hooks.
objectcrons?Record<string, CronSpec>
Handlers that run on a schedule in every luna of the type that has stored data. See CronSpec.
Record<string, CronSpec>{}idleTimeout?number | string
How long a luna stays awake without calls, in milliseconds or as a duration such as "5m".
number | string"30s"limits?{ memory?: string; cpu?: number; reserve?: boolean }
The most memory and CPU one luna may use. See Limits.
{ memory?: string; cpu?: number; reserve?: boolean }internet?boolean
Set false to refuse outbound requests from handlers and from this type's sandboxes.
booleantrueon?(listen) => ListenDef[]
The events and table changes this type listens to. See defineEvent.
(listen) => ListenDef[]pushes?Record<string, Ty>
The typed messages a luna sends its connected apps, with conn.push and ctx.broadcast.
Record<string, Ty>streams?Record<string, StreamDef>
Append-only logs made with stream(), used as ctx.streams.<name>.
Record<string, StreamDef>blobs?Record<string, BucketDef>
Buckets of files made with bucket(), used as ctx.blobs.<name>.
Record<string, BucketDef>sandboxes?Record<string, SandboxDef>
Linux machines made with sandbox(), used as ctx.sandboxes.<name>.
Record<string, SandboxDef>isolates?Record<string, IsolateDef>
Templates for running JavaScript you did not write, made with isolate(), used as ctx.isolates.<name>.
Record<string, IsolateDef>stateless?false
Leave it out for a keyed type. A stateless type sets true and takes StatelessSpec instead.
falsefalseHooks
Each hook gets the same ctx as a handler.
onMigrate?(ctx, change: { from: number; to: number }) => void | Promise<void>
Runs once as a luna with stored data moves to a new version, before anything else, in one transaction with the schema change.
(ctx, change: { from: number; to: number }) => void | Promise<void>onCreate?(ctx) => void | Promise<void>
Runs when a luna with no stored data wakes, before onWake.
(ctx) => void | Promise<void>onWake?(ctx) => void | Promise<void>
Runs each time a luna wakes.
(ctx) => void | Promise<void>onSleep?(ctx) => void | Promise<void>
Runs before a luna goes to sleep.
(ctx) => void | Promise<void>onDestroy?(ctx) => void | Promise<void>
Runs when the luna is destroyed.
(ctx) => void | Promise<void>onBeforeConnect?(ctx, request: ConnectRequest) => unknown
Runs before every call from outside. What it returns becomes ctx.caller.external, and ctx.fail(code) refuses the call.
(ctx, request: ConnectRequest) => unknownonConnect?(ctx, conn: Connection) => void | Promise<void>
Runs when an app opens a connection, after onBeforeConnect. Throwing refuses the connection.
(ctx, conn: Connection) => void | Promise<void>onDisconnect?(ctx, conn: Connection) => void | Promise<void>
Runs at least once when an app's connection closes, never when the luna closed it.
(ctx, conn: Connection) => void | Promise<void>onMessage?(ctx, conn: Connection, data: unknown) => void | Promise<void>
Runs for each raw message an app sends over its connection.
(ctx, conn: Connection, data: unknown) => void | Promise<void>onSshConnect?(ctx, request: SshConnectRequest) => boolean | { user?: string } | void | Promise<…>
Decides whether an SSH connection to one of the luna's sandboxes may open. Return true, or { user } to pick the account its programs run as, root by default.
(ctx, request: SshConnectRequest) => boolean | { user?: string } | void | Promise<…>ConnectRequest
What onBeforeConnect sees of a request from outside.
methodstring
The HTTP method.
stringpathstring
The request's path.
stringheadersRecord<string, string>
The request's headers, with lower-case names.
Record<string, string>queryRecord<string, string>
The query parameters.
Record<string, string>handlerstring
The handler the request calls.
stringapiTokenboolean
True when the request carried a secret API token.
booleanSshConnectRequest
What onSshConnect sees of an SSH connection.
sandboxstring
The sandbox, by the name the luna type gives it.
stringinstancestring | null
Which instance of the sandbox, or null for the first.
string | nullpublicKeystring
The key the connection proved it holds, as ssh-ed25519 AAAA….
stringfingerprintstring
The key's fingerprint, as ssh-keygen -l prints it.
stringaddressstring
Where the connection comes from.
stringCronSpec
schedulestring
Five cron fields, such as "0 3 * * *", or an interval such as "every 10m".
stringhandlerstring
The handler to run, one of this type's.
stringargs?Record<string, unknown>
The arguments the handler gets.
Record<string, unknown>{}tz?string
The time zone the cron fields are read in.
string"UTC"onMissed?"once" | "skip" | "all"
Runs it missed: once runs one, skip runs one only if it is under a minute late, all runs each.
"once" | "skip" | "all""once"overlap?"skip" | "queue" | "allow"
When a run is due while the last still runs: skip it, run it after, or run both at once.
"skip" | "queue" | "allow""skip"Limits
memory?string
The most memory one luna may use, such as "512MB" or "16GB". At least "64MB".
stringcpu?number
The most cores one luna may use, from 0.05 to 1024.
numberreserve?boolean
Holds all of memory and cpu from when the luna opens until it closes. Needs both.
booleanfalseStatelessSpec
A stateless type has no key, no tables and no transaction. Its handlers run many at once.
namestring
The luna type's name.
stringstatelesstrue
Makes the type stateless.
truehandlers(h: HandlerFactory<StatelessCtx>) => Record<string, Handler>
The handlers. Each gets a StatelessCtx.
(h: HandlerFactory<StatelessCtx>) => Record<string, Handler>visibility?"private" | "public"
As for a keyed type.
"private" | "public""private"internet?boolean
Set false to refuse outbound requests.
booleantruelimits?{ memory?: string; cpu?: number }
As for a keyed type, without reserve.
{ memory?: string; cpu?: number }isolates?Record<string, IsolateDef>
Isolate templates, used as ctx.isolates.<name>.
Record<string, IsolateDef>Luna
What defineLuna returns.
namestring
The luna type's name.
stringkind"luna"
Marks the value as a luna type.
"luna"specLunaSpec
The spec it was made from, without handlers.
LunaSpechandlersRecord<string, Handler>
The handlers, by name.
Record<string, Handler>changesRecord<string, TableChanges>
Each table's changes, to listen to or index, such as List.changes.items.
Record<string, TableChanges>package?string
The package the type came from, when definePackage marked it.
stringextrasLuna[]
Luna types made for this one, deployed with it.
Luna[]manifest()() => Record<string, unknown>
The type as Luna reads it on deploy.
() => Record<string, unknown>Good to know
- A luna type’s name starts with a capital letter and holds letters, digits and
_, up to 64 characters. - A key field is a required
t.string(),t.int(),t.uuid(),t.bytes()ort.enum(). A handler argument cannot share a key field’s name. onSleepandonDestroymay run for 10 seconds, andonMigratefor 60 seconds. A hook that runs longer fails.- If
onMigratethrows, nothing it did is kept and the luna stays on its old version until a newer one is deployed. onBeforeConnectruns for calls from outside Luna only. Calls between lunas skip it. WithoutonSshConnect, every SSH connection is refused.internet: falseon any luna type turns off outbound requests from handlers of every luna type deployed with it, because their handlers share one runtime. See Reach the internet. A deploy that sets it on some types and not others asks you to confirm first.- With
reserve: true, a luna that opens waits for a machine with that much free, and fails withNoRoomif none has it. - A stateless type given any other option, such as
keyorschema, throws when it is defined. Its handlers cannot usequery,shared,exclusive,durableorrequires.
Examples
Set up a new luna
onCreate runs before the first call to a luna with no stored data. Its writes create the luna.
import { defineLuna, t, table } from "luna";
export const Board = defineLuna({
name: "Board",
key: { id: t.string() },
schema: {
settings: table({ title: t.string(), created: t.timestamp() }, { singleRow: true }),
cards: table({ id: t.id(), text: t.string(), archived: t.bool().default(false) }),
},
hooks: {
onCreate(ctx) {
ctx.db.settings.set({ title: `Board ${ctx.key.id}`, created: ctx.now() });
},
},
handlers: (h) => ({
add: h({ args: { text: t.string() } }, (ctx, { text }) => ctx.db.cards.insert({ text })),
}),
});
Fix data on a new version
change.from is the version the luna ran before.
hooks: {
onMigrate(ctx, { from }) {
if (from < 3) ctx.exec("UPDATE cards SET text = trim(text)");
},
},
Run a handler every night
handlers: (h) => ({
tidy: h({}, (ctx) => {
ctx.db.cards.delete({ where: { archived: true } });
}),
}),
crons: {
nightly: { schedule: "0 3 * * *", handler: "tidy", tz: "Europe/Paris" },
},
Give each luna more room
import { defineLuna, t, table } from "luna";
export const Report = defineLuna({
name: "Report",
key: { id: t.string() },
limits: { memory: "4GB", cpu: 2 },
idleTimeout: "5m",
schema: { rows: table({ id: t.id(), value: t.float() }) },
handlers: (h) => ({
total: h({ query: true }, (ctx) => ctx.db.rows.find().reduce((sum, r) => sum + r.value, 0)),
}),
});
Define a stateless type
import { defineLuna, t } from "luna";
import { List } from "./list.ts";
export const Stats = defineLuna({
name: "Stats",
stateless: true,
visibility: "public",
handlers: (h) => ({
count: h({ args: { lists: t.array(t.string()) } }, async (ctx, { lists }) => {
const all = await Promise.all(lists.map((id) => ctx.call(List, { id }).all({})));
return all.reduce((n, items) => n + items.length, 0);
}),
}),
});