Skip to content
Luna
Esc
↑↓navigate↵open⌘Jpreview
On this page

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

PropType
namestring

The luna type's name, used in every URL and call.

Typestring
handlers(h: HandlerFactory) => Record<string, Handler>

Returns the handlers, each made with h(spec, run). See Handler spec.

Type(h: HandlerFactory) => Record<string, Handler>
key?Record<string, Ty>

The key fields that pick one luna. With none, the type has exactly one luna.

TypeRecord<string, Ty>
Default{}
visibility?"private" | "public"

Public types can be called with a publishable key. Private ones need a secret token.

Type"private" | "public"
Default"private"
schema?Record<string, TableDef>

Each luna's tables, made with table().

TypeRecord<string, TableDef>
Default{}
hooks?object

Functions that run at points in a luna's life and on connections. See Hooks.

Typeobject
crons?Record<string, CronSpec>

Handlers that run on a schedule in every luna of the type that has stored data. See CronSpec.

TypeRecord<string, CronSpec>
Default{}
idleTimeout?number | string

How long a luna stays awake without calls, in milliseconds or as a duration such as "5m".

Typenumber | string
Default"30s"
limits?{ memory?: string; cpu?: number; reserve?: boolean }

The most memory and CPU one luna may use. See Limits.

Type{ memory?: string; cpu?: number; reserve?: boolean }
internet?boolean

Set false to refuse outbound requests from handlers and from this type's sandboxes.

Typeboolean
Defaulttrue
on?(listen) => ListenDef[]

The events and table changes this type listens to. See defineEvent.

Type(listen) => ListenDef[]
pushes?Record<string, Ty>

The typed messages a luna sends its connected apps, with conn.push and ctx.broadcast.

TypeRecord<string, Ty>
streams?Record<string, StreamDef>

Append-only logs made with stream(), used as ctx.streams.<name>.

TypeRecord<string, StreamDef>
blobs?Record<string, BucketDef>

Buckets of files made with bucket(), used as ctx.blobs.<name>.

TypeRecord<string, BucketDef>
sandboxes?Record<string, SandboxDef>

Linux machines made with sandbox(), used as ctx.sandboxes.<name>.

TypeRecord<string, SandboxDef>
isolates?Record<string, IsolateDef>

Templates for running JavaScript you did not write, made with isolate(), used as ctx.isolates.<name>.

TypeRecord<string, IsolateDef>
stateless?false

Leave it out for a keyed type. A stateless type sets true and takes StatelessSpec instead.

Typefalse
Defaultfalse

Hooks

Each hook gets the same ctx as a handler.

PropType
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.

Type(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.

Type(ctx) => void | Promise<void>
onWake?(ctx) => void | Promise<void>

Runs each time a luna wakes.

Type(ctx) => void | Promise<void>
onSleep?(ctx) => void | Promise<void>

Runs before a luna goes to sleep.

Type(ctx) => void | Promise<void>
onDestroy?(ctx) => void | Promise<void>

Runs when the luna is destroyed.

Type(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.

Type(ctx, request: ConnectRequest) => unknown
onConnect?(ctx, conn: Connection) => void | Promise<void>

Runs when an app opens a connection, after onBeforeConnect. Throwing refuses the connection.

Type(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.

Type(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.

Type(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.

Type(ctx, request: SshConnectRequest) => boolean | { user?: string } | void | Promise<…>

ConnectRequest

What onBeforeConnect sees of a request from outside.

PropType
methodstring

The HTTP method.

Typestring
pathstring

The request's path.

Typestring
headersRecord<string, string>

The request's headers, with lower-case names.

TypeRecord<string, string>
queryRecord<string, string>

The query parameters.

TypeRecord<string, string>
handlerstring

The handler the request calls.

Typestring
apiTokenboolean

True when the request carried a secret API token.

Typeboolean

SshConnectRequest

What onSshConnect sees of an SSH connection.

PropType
sandboxstring

The sandbox, by the name the luna type gives it.

Typestring
instancestring | null

Which instance of the sandbox, or null for the first.

Typestring | null
publicKeystring

The key the connection proved it holds, as ssh-ed25519 AAAA….

Typestring
fingerprintstring

The key's fingerprint, as ssh-keygen -l prints it.

Typestring
addressstring

Where the connection comes from.

Typestring

CronSpec

PropType
schedulestring

Five cron fields, such as "0 3 * * *", or an interval such as "every 10m".

Typestring
handlerstring

The handler to run, one of this type's.

Typestring
args?Record<string, unknown>

The arguments the handler gets.

TypeRecord<string, unknown>
Default{}
tz?string

The time zone the cron fields are read in.

Typestring
Default"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.

Type"once" | "skip" | "all"
Default"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.

Type"skip" | "queue" | "allow"
Default"skip"

Limits

PropType
memory?string

The most memory one luna may use, such as "512MB" or "16GB". At least "64MB".

Typestring
cpu?number

The most cores one luna may use, from 0.05 to 1024.

Typenumber
reserve?boolean

Holds all of memory and cpu from when the luna opens until it closes. Needs both.

Typeboolean
Defaultfalse

StatelessSpec

A stateless type has no key, no tables and no transaction. Its handlers run many at once.

PropType
namestring

The luna type's name.

Typestring
statelesstrue

Makes the type stateless.

Typetrue
handlers(h: HandlerFactory<StatelessCtx>) => Record<string, Handler>

The handlers. Each gets a StatelessCtx.

Type(h: HandlerFactory<StatelessCtx>) => Record<string, Handler>
visibility?"private" | "public"

As for a keyed type.

Type"private" | "public"
Default"private"
internet?boolean

Set false to refuse outbound requests.

Typeboolean
Defaulttrue
limits?{ memory?: string; cpu?: number }

As for a keyed type, without reserve.

Type{ memory?: string; cpu?: number }
isolates?Record<string, IsolateDef>

Isolate templates, used as ctx.isolates.<name>.

TypeRecord<string, IsolateDef>

Luna

What defineLuna returns.

PropType
namestring

The luna type's name.

Typestring
kind"luna"

Marks the value as a luna type.

Type"luna"
specLunaSpec

The spec it was made from, without handlers.

TypeLunaSpec
handlersRecord<string, Handler>

The handlers, by name.

TypeRecord<string, Handler>
changesRecord<string, TableChanges>

Each table's changes, to listen to or index, such as List.changes.items.

TypeRecord<string, TableChanges>
package?string

The package the type came from, when definePackage marked it.

Typestring
extrasLuna[]

Luna types made for this one, deployed with it.

TypeLuna[]
manifest()() => Record<string, unknown>

The type as Luna reads it on deploy.

Type() => 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() or t.enum(). A handler argument cannot share a key field’s name.
  • onSleep and onDestroy may run for 10 seconds, and onMigrate for 60 seconds. A hook that runs longer fails.
  • If onMigrate throws, nothing it did is kept and the luna stays on its old version until a newer one is deployed.
  • onBeforeConnect runs for calls from outside Luna only. Calls between lunas skip it. Without onSshConnect, every SSH connection is refused.
  • internet: false on 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 with NoRoom if none has it.
  • A stateless type given any other option, such as key or schema, throws when it is defined. Its handlers cannot use query, shared, exclusive, durable or requires.

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

Was this page helpful?