ctx
Every member of the ctx a handler or hook receives, grouped by what it does, with its option types and the members of a stateless handler's ctx.
ctx is the first argument of every handler and hook. It holds the luna’s data, what is known about the call, and every way to act from the handler.
import { defineLuna, t, table } from "luna";
import { Wallet } from "./wallet.ts";
export const Shop = defineLuna({
name: "Shop",
key: { id: t.string() },
schema: { orders: table({ id: t.id(), user: t.string(), amount: t.int(), paid: t.bool().default(false) }) },
handlers: (h) => ({
buy: h({ args: { user: t.string(), amount: t.int() } }, async (ctx, { user, amount }) => {
const order = ctx.db.orders.insert({ user, amount });
await ctx.call(Wallet, { id: user }).charge({ amount }, { timeout: "5s", idempotencyKey: `order-${order}` });
ctx.db.orders.update({ where: { id: order }, set: { paid: true } });
ctx.schedule({ after: "1d", handler: "remind", args: { order }, id: `remind-${order}` });
return order;
}),
remind: h({ args: { order: t.int() } }, (ctx, { order }) => {
console.log("reminding about", order);
}),
}),
});
Reference
The call
keyobject
The key fields of the luna the call runs on.
objectisNewboolean
True until the luna first keeps a write.
booleancallerCaller
Who made the call. See Caller.
Callerhandlerstring
The handler's name.
stringlunaTypestring
The luna type's name.
stringtenantstring
The tenant the luna belongs to.
stringcallIdstring
An id for this call, different on every call.
stringtraceIdstring
The trace the call belongs to, 32 hex digits, to match with logs and other systems.
stringinstanceIdstring
Luna's id for this luna, the same on every call to it.
stringversionnumber
The version of the app's code the call runs on.
numbergenerationnumber
The number of the luna's current copy of its data, which changes when the data is restored.
numberattemptnumber
1 for a call. A retried message counts up.
numberfire{ scheduleId: string; scheduledForMs: number; lateByMs: number } | null
For a call from a schedule or cron: which one, when it was due, and how late it ran.
{ scheduleId: string; scheduledForMs: number; lateByMs: number } | nulldeadlinenumber | null
When the call must answer by, in milliseconds since the epoch.
number | nullrequestLunaRequest | undefined
The HTTP request, for a call that came through a route.
LunaRequest | undefinedabortSignalAbortSignal
Fires when the caller goes away, such as an HTTP client that disconnected.
AbortSignalisReplicaboolean
True when a read copy of the luna answers the call.
booleanenvReadonly<Record<string, string>>
The secrets set with luna secrets set.
Readonly<Record<string, string>>Data
Tables are on ctx.db. SQL is in Run SQL, threads in attach and indexes in defineIndex.
dbDb
The luna's tables, one Table or SingleRow each.
Dbexec(sql, params?)(sql: string, params?: unknown[] | Record<string, unknown>) => { rows; changes; lastInsertRowid }
Runs one SQL statement, with ? or :name parameters.
(sql: string, params?: unknown[] | Record<string, unknown>) => { rows; changes; lastInsertRowid }sql`…`(strings, ...values) => Record<string, unknown>[]
Runs SQL written as a tagged template. Each value becomes a parameter.
(strings, ...values) => Record<string, unknown>[]transaction(fn)<T>(fn: () => T) => T
Runs a synchronous function whose writes all roll back if it throws.
<T>(fn: () => T) => Tthread()() => ThreadHandle
A handle another thread passes to attach() to reach this luna's tables.
() => ThreadHandleposition()() => number
A commit position covering the writes so far, for a read sent with luna-read: at-least=<POSITION>.
() => numberindex(index)(index: Index) => IndexQuery
Reads an index made with defineIndex.
(index: Index) => IndexQuerybookmark()() => Bookmark
Where this handler's writes will stand in the indexes, to read them back with after.
() => BookmarkCalls and messages
Details are in Call another luna and Call across tenants.
call(luna, key)(luna: Luna | string, key) => { [handler]: (args, opts?: CallOptions) => Promise<R> }
Calls a handler on a luna and waits for its result.
(luna: Luna | string, key) => { [handler]: (args, opts?: CallOptions) => Promise<R> }send(luna, key)(luna: Luna | string, key) => { [handler]: (args, opts?: SendOptions) => string }
Sends a message that runs later, once this handler succeeds. Returns its id.
(luna: Luna | string, key) => { [handler]: (args, opts?: SendOptions) => string }list(luna, opts?)(luna, opts?: { prefix?; cursor?; limit? }) => Promise<{ keys; cursor }>
The keys of lunas of a type that exist, in key order, 100 a page by default and 1,000 at most.
(luna, opts?: { prefix?; cursor?; limit? }) => Promise<{ keys; cursor }>fail(code, data?, opts?)(code: string, data?: unknown, opts?: { keep?: boolean }) => never
Fails the call with a declared error. With keep: true, the call's writes and messages are kept.
(code: string, data?: unknown, opts?: { keep?: boolean }) => nevertenants{ get(name).luna(type).at(key).call(handler, args?, opts?) }
Calls a luna in another tenant of the environment.
{ get(name).luna(type).at(key).call(handler, args?, opts?) }services{ get(name).at(key).call(handler, args?, opts?) }
Calls what the environment's default tenant has granted this tenant, by service name.
{ get(name).at(key).call(handler, args?, opts?) }Time and randomness
In a durable run, each value is recorded and the same value comes back when the run replays.
now()() => number
The time in milliseconds since the epoch.
() => numberrandom()() => number
A number from 0 up to 1, as Math.random().
() => numberuuid()() => string
A random UUID.
() => stringSchedules
Details are in Schedule a handler.
schedule(spec)(spec: ScheduleSpec) => string
Schedules a handler once or on a cron, and returns the schedule's id.
(spec: ScheduleSpec) => stringschedules.list()() => ScheduleInfo[]
The luna's schedules, type-level crons included.
() => ScheduleInfo[]schedules.cancel(id)(id: string) => boolean
Cancels a schedule. False if there was none.
(id: string) => booleanschedules.reschedule(id, at)(id: string, at: Date | number) => boolean
Moves a schedule's next run. False if there was none.
(id: string, at: Date | number) => booleanDurable runs
These work in a handler declared durable: true. Details are in Run durable work and Wait for a signal.
runIdstring | null
The durable run this call executes, or null.
string | nullstep(name, fn, opts?)<T>(name: string, fn: (step: StepContext) => T | Promise<T>, opts?: StepOptions) => Promise<T>
Runs fn once in the run and replays its result after.
<T>(name: string, fn: (step: StepContext) => T | Promise<T>, opts?: StepOptions) => Promise<T>sleep(duration)(d: number | string) => Promise<void>
Waits durably for a duration, such as "1h".
(d: number | string) => Promise<void>sleepUntil(at)(at: Date | number) => Promise<void>
Waits durably until a time.
(at: Date | number) => Promise<void>waitFor(name, opts?)<T>(name: string, opts?: { timeout?: number | string }) => Promise<T | undefined>
Waits for a signal, and gives undefined after timeout. Outside a durable run, it waits in memory for at most 15 minutes.
<T>(name: string, opts?: { timeout?: number | string }) => Promise<T | undefined>promise()<T>() => DurablePromise<T>
A promise that a signal sent to this run resolves.
<T>() => DurablePromise<T>continueAsNew(args)(args: Record<string, unknown>) => Promise<never>
Ends the run's history and starts the run again with args.
(args: Record<string, unknown>) => Promise<never>runs(luna, key)(luna, key) => Runs
Gets, lists, cancels and signals the durable runs of a luna.
(luna, key) => Runssignal(luna, key, name, payload?)(luna, key, name: string, payload?: unknown) => Promise<number>
Sends a signal to every run or wait for name on a luna, and returns how many got it.
(luna, key, name: string, payload?: unknown) => Promise<number>Events and streams
Details are in defineEvent and stream.
emit(event, payload)(event: EventDef, payload) => number
Emits an event once the handler's writes are kept, and returns its place in this luna's log of it.
(event: EventDef, payload) => numberstreams{ [name]: Stream }
The luna's streams, by the name the luna type gives them.
{ [name]: Stream }subscribe(luna, key, stream, opts)(luna, key, stream: string, opts: { handler: string; from?: number }) => string
Runs a handler here for each entry of a stream, in order, and returns the subscription's id.
(luna, key, stream: string, opts: { handler: string; from?: number }) => stringunsubscribe(id)(id: string) => boolean
Stops following a stream. False if there was no such subscription.
(id: string) => booleansubscriptions()() => SubscriptionInfo[]
The streams this luna follows.
() => SubscriptionInfo[]Connections
Details are in Open a connection, Push to connected apps and Connect to an outside WebSocket.
connectionConnection | undefined
The app connection the call came over, while it is open.
Connection | undefinedconnections{ list(opts?: { tag? }): Connection[]; get(id): Connection | undefined }
The luna's open app connections.
{ list(opts?: { tag? }): Connection[]; get(id): Connection | undefined }broadcast(name, data, opts?)(name: string, data: unknown, opts?: { tags?: string[]; except?: string | Connection }) => void
Pushes a declared push to every connected app, or to those with any of tags.
(name: string, data: unknown, opts?: { tags?: string[]; except?: string | Connection }) => voidsockets{ open(url, opts); list(); get(id) }
Outbound WebSockets the luna opened.
{ open(url, opts); list(); get(id) }Files and code
Details are in bucket, isolate and sandbox.
blobs{ [name]: Bucket }
The luna's buckets of files.
{ [name]: Bucket }isolates{ [name]: Isolate }
The luna type's isolate templates, to run JavaScript you did not write.
{ [name]: Isolate }sandboxes{ [name]: Sandbox }
The luna's sandboxes.
{ [name]: Sandbox }The luna’s life
sleep()() => void
Called with no argument, puts the luna to sleep once nothing runs on it.
() => voiddestroy()() => void
Deletes the luna's data, messages and schedules once its running handlers finish.
() => voidCaller
One of four shapes. Test which with in, such as "luna" in ctx.caller.
{ external, connection? }{ external: unknown; connection?: string }
A call from outside Luna. external is what onBeforeConnect returned, or null, and connection is set for a call over an app's connection.
{ external: unknown; connection?: string }{ luna, key }{ luna: string; key: Record<string, unknown> }
A call or message from a luna, by its type and key.
{ luna: string; key: Record<string, unknown> }{ schedule }{ schedule: true }
A schedule or cron fired the call.
{ schedule: true }{ system }{ system: true }
Luna itself called, such as for a hook.
{ system: true }CallOptions
timeout?number | string
How long to wait for the result, in milliseconds or as a duration.
number | string"60s"idempotencyKey?string
A retried call with the same key returns the first call's result without running again.
stringSendOptions
delay?number | string
How long to wait before delivering.
number | stringmaxAttempts?number
How many times to try delivering, at least 1.
number10firstRetry?number | string
How long to wait before the first retry.
number | string"169s"dedupeKey?string
Delivers once, however many messages share this key.
stringScheduleSpec
Give one of after, at or cron.
handlerstring
The handler to run.
stringafter?number | string
Runs once after this delay, such as "10m".
number | stringat?Date | number
Runs once at this time.
Date | numbercron?string
Runs on this cron schedule.
stringargs?Record<string, unknown>
The handler's arguments.
Record<string, unknown>{}id?string
The schedule's id. Scheduling again with the same id replaces it.
stringtarget?{ luna: Luna | string; key: Record<string, unknown> }
Another luna to run the handler on.
{ luna: Luna | string; key: Record<string, unknown> }this lunatz?string
The time zone a cron is read in.
string"UTC"onMissed?"once" | "skip" | "all"
What a cron does with runs it missed.
"once" | "skip" | "all""once"overlap?"skip" | "queue" | "allow"
What a cron does when a run is due while the last one still runs.
"skip" | "queue" | "allow""skip"StepOptions
attempts?number
Tries in all for a step that throws an error other than a declared one.
number3backoff?number
Milliseconds to wait before the first retry, doubling each time.
number1000timeout?number | string
How long one try may take. A slower try fails and its signal fires.
number | stringcompensate?(result: T) => unknown
Undoes the step if the run fails or is cancelled later.
(result: T) => unknownStatelessCtx
A stateless handler’s ctx has caller, callId, traceId, handler, lunaType, tenant, version, deadline, request, abortSignal, env, call, tenants, services, isolates, now(), random(), uuid() and fail(code, data?). They work as above. It has no key, db, send or anything else on this page, and fail takes no keep.
Good to know
- Table reads and writes run at once, without
await. Code between twoawaits runs with no other call on the luna in between. At eachawait, other calls may run and see what the handler has written so far. - When a handler fails, its writes are undone, except on a row another call changed since, which keeps that call’s value. Its messages, events and pushes never go. Calls to other lunas and requests outside Luna that it already made stay done.
fail(code, data, { keep: true })keeps its writes and messages. transactiontakes a synchronous function. Its writes roll back if it throws, and the handler goes on.
Examples
Know who called
who: h({}, (ctx) => {
if ("luna" in ctx.caller) return `the ${ctx.caller.luna} luna`;
if ("external" in ctx.caller) return "an app or a server";
if ("schedule" in ctx.caller) return "a schedule";
return "Luna itself";
}),
Undo some writes and carry on
move: h({ args: { from: t.int(), to: t.int() } }, (ctx, { from, to }) => {
try {
ctx.transaction(() => {
ctx.db.orders.update({ where: { id: from }, set: { amount: 0 } });
if (!ctx.db.orders.get(to)) throw new Error("no such order");
});
} catch {
return false;
}
return true;
}),
Send a message with fewer retries
refund: h({ args: { user: t.string(), amount: t.int(), order: t.int() } }, (ctx, { user, amount, order }) => {
return ctx.send(Wallet, { id: user }).credit({ amount }, { maxAttempts: 3, firstRetry: "30s", dedupeKey: `refund-${order}` });
}),
Use a secret and stop when the caller leaves
pay: h({ args: { amount: t.int() } }, async (ctx, { amount }) => {
const res = await fetch("https://api.example.com/charge", {
method: "POST",
headers: { authorization: `Bearer ${ctx.env.PAYMENTS_KEY}` },
body: JSON.stringify({ amount }),
signal: ctx.abortSignal,
});
return res.ok;
}),