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

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

PropType
keyobject

The key fields of the luna the call runs on.

Typeobject
isNewboolean

True until the luna first keeps a write.

Typeboolean
callerCaller

Who made the call. See Caller.

TypeCaller
handlerstring

The handler's name.

Typestring
lunaTypestring

The luna type's name.

Typestring
tenantstring

The tenant the luna belongs to.

Typestring
callIdstring

An id for this call, different on every call.

Typestring
traceIdstring

The trace the call belongs to, 32 hex digits, to match with logs and other systems.

Typestring
instanceIdstring

Luna's id for this luna, the same on every call to it.

Typestring
versionnumber

The version of the app's code the call runs on.

Typenumber
generationnumber

The number of the luna's current copy of its data, which changes when the data is restored.

Typenumber
attemptnumber

1 for a call. A retried message counts up.

Typenumber
fire{ 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.

Type{ scheduleId: string; scheduledForMs: number; lateByMs: number } | null
deadlinenumber | null

When the call must answer by, in milliseconds since the epoch.

Typenumber | null
requestLunaRequest | undefined

The HTTP request, for a call that came through a route.

TypeLunaRequest | undefined
abortSignalAbortSignal

Fires when the caller goes away, such as an HTTP client that disconnected.

TypeAbortSignal
isReplicaboolean

True when a read copy of the luna answers the call.

Typeboolean
envReadonly<Record<string, string>>

The secrets set with luna secrets set.

TypeReadonly<Record<string, string>>

Data

Tables are on ctx.db. SQL is in Run SQL, threads in attach and indexes in defineIndex.

PropType
dbDb

The luna's tables, one Table or SingleRow each.

TypeDb
exec(sql, params?)(sql: string, params?: unknown[] | Record<string, unknown>) => { rows; changes; lastInsertRowid }

Runs one SQL statement, with ? or :name parameters.

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

Type(strings, ...values) => Record<string, unknown>[]
transaction(fn)<T>(fn: () => T) => T

Runs a synchronous function whose writes all roll back if it throws.

Type<T>(fn: () => T) => T
thread()() => ThreadHandle

A handle another thread passes to attach() to reach this luna's tables.

Type() => ThreadHandle
position()() => number

A commit position covering the writes so far, for a read sent with luna-read: at-least=<POSITION>.

Type() => number
index(index)(index: Index) => IndexQuery

Reads an index made with defineIndex.

Type(index: Index) => IndexQuery
bookmark()() => Bookmark

Where this handler's writes will stand in the indexes, to read them back with after.

Type() => Bookmark

Calls and messages

Details are in Call another luna and Call across tenants.

PropType
call(luna, key)(luna: Luna | string, key) => { [handler]: (args, opts?: CallOptions) => Promise<R> }

Calls a handler on a luna and waits for its result.

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

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

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

Type(code: string, data?: unknown, opts?: { keep?: boolean }) => never
tenants{ get(name).luna(type).at(key).call(handler, args?, opts?) }

Calls a luna in another tenant of the environment.

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

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

PropType
now()() => number

The time in milliseconds since the epoch.

Type() => number
random()() => number

A number from 0 up to 1, as Math.random().

Type() => number
uuid()() => string

A random UUID.

Type() => string

Schedules

Details are in Schedule a handler.

PropType
schedule(spec)(spec: ScheduleSpec) => string

Schedules a handler once or on a cron, and returns the schedule's id.

Type(spec: ScheduleSpec) => string
schedules.list()() => ScheduleInfo[]

The luna's schedules, type-level crons included.

Type() => ScheduleInfo[]
schedules.cancel(id)(id: string) => boolean

Cancels a schedule. False if there was none.

Type(id: string) => boolean
schedules.reschedule(id, at)(id: string, at: Date | number) => boolean

Moves a schedule's next run. False if there was none.

Type(id: string, at: Date | number) => boolean

Durable runs

These work in a handler declared durable: true. Details are in Run durable work and Wait for a signal.

PropType
runIdstring | null

The durable run this call executes, or null.

Typestring | null
step(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.

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

Type(d: number | string) => Promise<void>
sleepUntil(at)(at: Date | number) => Promise<void>

Waits durably until a time.

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

Type<T>(name: string, opts?: { timeout?: number | string }) => Promise<T | undefined>
promise()<T>() => DurablePromise<T>

A promise that a signal sent to this run resolves.

Type<T>() => DurablePromise<T>
continueAsNew(args)(args: Record<string, unknown>) => Promise<never>

Ends the run's history and starts the run again with args.

Type(args: Record<string, unknown>) => Promise<never>
runs(luna, key)(luna, key) => Runs

Gets, lists, cancels and signals the durable runs of a luna.

Type(luna, key) => Runs
signal(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.

Type(luna, key, name: string, payload?: unknown) => Promise<number>

Events and streams

Details are in defineEvent and stream.

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

Type(event: EventDef, payload) => number
streams{ [name]: Stream }

The luna's streams, by the name the luna type gives them.

Type{ [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.

Type(luna, key, stream: string, opts: { handler: string; from?: number }) => string
unsubscribe(id)(id: string) => boolean

Stops following a stream. False if there was no such subscription.

Type(id: string) => boolean
subscriptions()() => SubscriptionInfo[]

The streams this luna follows.

Type() => SubscriptionInfo[]

Connections

Details are in Open a connection, Push to connected apps and Connect to an outside WebSocket.

PropType
connectionConnection | undefined

The app connection the call came over, while it is open.

TypeConnection | undefined
connections{ list(opts?: { tag? }): Connection[]; get(id): Connection | undefined }

The luna's open app connections.

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

Type(name: string, data: unknown, opts?: { tags?: string[]; except?: string | Connection }) => void
sockets{ open(url, opts); list(); get(id) }

Outbound WebSockets the luna opened.

Type{ open(url, opts); list(); get(id) }

Files and code

Details are in bucket, isolate and sandbox.

PropType
blobs{ [name]: Bucket }

The luna's buckets of files.

Type{ [name]: Bucket }
isolates{ [name]: Isolate }

The luna type's isolate templates, to run JavaScript you did not write.

Type{ [name]: Isolate }
sandboxes{ [name]: Sandbox }

The luna's sandboxes.

Type{ [name]: Sandbox }

The luna’s life

PropType
sleep()() => void

Called with no argument, puts the luna to sleep once nothing runs on it.

Type() => void
destroy()() => void

Deletes the luna's data, messages and schedules once its running handlers finish.

Type() => void

Caller

One of four shapes. Test which with in, such as "luna" in ctx.caller.

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

Type{ external: unknown; connection?: string }
{ luna, key }{ luna: string; key: Record<string, unknown> }

A call or message from a luna, by its type and key.

Type{ luna: string; key: Record<string, unknown> }
{ schedule }{ schedule: true }

A schedule or cron fired the call.

Type{ schedule: true }
{ system }{ system: true }

Luna itself called, such as for a hook.

Type{ system: true }

CallOptions

PropType
timeout?number | string

How long to wait for the result, in milliseconds or as a duration.

Typenumber | string
Default"60s"
idempotencyKey?string

A retried call with the same key returns the first call's result without running again.

Typestring

SendOptions

PropType
delay?number | string

How long to wait before delivering.

Typenumber | string
maxAttempts?number

How many times to try delivering, at least 1.

Typenumber
Default10
firstRetry?number | string

How long to wait before the first retry.

Typenumber | string
Default"169s"
dedupeKey?string

Delivers once, however many messages share this key.

Typestring

ScheduleSpec

Give one of after, at or cron.

PropType
handlerstring

The handler to run.

Typestring
after?number | string

Runs once after this delay, such as "10m".

Typenumber | string
at?Date | number

Runs once at this time.

TypeDate | number
cron?string

Runs on this cron schedule.

Typestring
args?Record<string, unknown>

The handler's arguments.

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

The schedule's id. Scheduling again with the same id replaces it.

Typestring
target?{ luna: Luna | string; key: Record<string, unknown> }

Another luna to run the handler on.

Type{ luna: Luna | string; key: Record<string, unknown> }
Defaultthis luna
tz?string

The time zone a cron is read in.

Typestring
Default"UTC"
onMissed?"once" | "skip" | "all"

What a cron does with runs it missed.

Type"once" | "skip" | "all"
Default"once"
overlap?"skip" | "queue" | "allow"

What a cron does when a run is due while the last one still runs.

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

StepOptions

PropType
attempts?number

Tries in all for a step that throws an error other than a declared one.

Typenumber
Default3
backoff?number

Milliseconds to wait before the first retry, doubling each time.

Typenumber
Default1000
timeout?number | string

How long one try may take. A slower try fails and its signal fires.

Typenumber | string
compensate?(result: T) => unknown

Undoes the step if the run fails or is cancelled later.

Type(result: T) => unknown

StatelessCtx

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 two awaits runs with no other call on the luna in between. At each await, 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.
  • transaction takes 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;
}),

Was this page helpful?