---
title: ctx
description: 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.
related:
  - /lunas/write-handlers
  - /sdk/db
  - /lunas/call-another-luna
---

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

```ts luna/lunas/shop.ts
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

| Prop | Type | Default | Description |
| - | - | - | - |
| `key` | `object` | - | The key fields of the luna the call runs on. |
| `isNew` | `boolean` | - | True until the luna first keeps a write. |
| `caller` | `Caller` | - | Who made the call. See Caller. |
| `handler` | `string` | - | The handler's name. |
| `lunaType` | `string` | - | The luna type's name. |
| `tenant` | `string` | - | The tenant the luna belongs to. |
| `callId` | `string` | - | An id for this call, different on every call. |
| `traceId` | `string` | - | The trace the call belongs to, 32 hex digits, to match with logs and other systems. |
| `instanceId` | `string` | - | Luna's id for this luna, the same on every call to it. |
| `version` | `number` | - | The version of the app's code the call runs on. |
| `generation` | `number` | - | The number of the luna's current copy of its data, which changes when the data is restored. |
| `attempt` | `number` | - | 1 for a call. A retried message counts up. |
| `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. |
| `deadline` | `number \| null` | - | When the call must answer by, in milliseconds since the epoch. |
| `request` | `LunaRequest \| undefined` | - | The HTTP request, for a call that came through a route. |
| `abortSignal` | `AbortSignal` | - | Fires when the caller goes away, such as an HTTP client that disconnected. |
| `isReplica` | `boolean` | - | True when a read copy of the luna answers the call. |
| `env` | `Readonly<Record<string, string>>` | - | The secrets set with luna secrets set. |

### Data

Tables are on [ctx.db](/sdk/db). SQL is in [Run SQL](/data/run-sql), threads in [attach](/sdk/attach) and indexes in [defineIndex](/sdk/define-index).

| Prop | Type | Default | Description |
| - | - | - | - |
| `db` | `Db` | - | The luna's tables, one Table or SingleRow each. |
| `exec(sql, params?)` | `(sql: string, params?: unknown[] \| Record<string, unknown>) => { rows; changes; lastInsertRowid }` | - | Runs one SQL statement, with ? or :name parameters. |
| sql`…` | `(strings, ...values) => Record<string, unknown>[]` | - | Runs SQL written as a tagged template. Each value becomes a parameter. |
| `transaction(fn)` | `<T>(fn: () => T) => T` | - | Runs a synchronous function whose writes all roll back if it throws. |
| `thread()` | `() => ThreadHandle` | - | A handle another thread passes to attach() to reach this luna's tables. |
| `position()` | `() => number` | - | A commit position covering the writes so far, for a read sent with luna-read: at-least=<POSITION>. |
| `index(index)` | `(index: Index) => IndexQuery` | - | Reads an index made with defineIndex. |
| `bookmark()` | `() => Bookmark` | - | Where this handler's writes will stand in the indexes, to read them back with after. |

### Calls and messages

Details are in [Call another luna](/lunas/call-another-luna) and [Call across tenants](/platforms/call-across-tenants).

| Prop | Type | Default | Description |
| - | - | - | - |
| `call(luna, key)` | `(luna: Luna \| string, key) => { [handler]: (args, opts?: CallOptions) => Promise<R> }` | - | Calls a handler on a luna and waits for its result. |
| `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. |
| `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. |
| `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. |
| `tenants` | `{ get(name).luna(type).at(key).call(handler, args?, opts?) }` | - | Calls a luna in another tenant of the environment. |
| `services` | `{ get(name).at(key).call(handler, args?, opts?) }` | - | Calls what the environment's default tenant has granted this tenant, by service name. |

### Time and randomness

In a durable run, each value is recorded and the same value comes back when the run replays.

| Prop | Type | Default | Description |
| - | - | - | - |
| `now()` | `() => number` | - | The time in milliseconds since the epoch. |
| `random()` | `() => number` | - | A number from 0 up to 1, as Math.random(). |
| `uuid()` | `() => string` | - | A random UUID. |

### Schedules

Details are in [Schedule a handler](/background/schedule-a-handler).

| Prop | Type | Default | Description |
| - | - | - | - |
| `schedule(spec)` | `(spec: ScheduleSpec) => string` | - | Schedules a handler once or on a cron, and returns the schedule's id. |
| `schedules.list()` | `() => ScheduleInfo[]` | - | The luna's schedules, type-level crons included. |
| `schedules.cancel(id)` | `(id: string) => boolean` | - | Cancels a schedule. False if there was none. |
| `schedules.reschedule(id, at)` | `(id: string, at: Date \| number) => boolean` | - | Moves a schedule's next run. False if there was none. |

### Durable runs

These work in a handler declared `durable: true`. Details are in [Run durable work](/background/run-durable-work) and [Wait for a signal](/background/wait-for-a-signal).

| Prop | Type | Default | Description |
| - | - | - | - |
| `runId` | `string \| null` | - | The durable run this call executes, or 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. |
| `sleep(duration)` | `(d: number \| string) => Promise<void>` | - | Waits durably for a duration, such as "1h". |
| `sleepUntil(at)` | `(at: Date \| number) => Promise<void>` | - | Waits durably until a time. |
| `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. |
| `promise()` | `<T>() => DurablePromise<T>` | - | A promise that a signal sent to this run resolves. |
| `continueAsNew(args)` | `(args: Record<string, unknown>) => Promise<never>` | - | Ends the run's history and starts the run again with args. |
| `runs(luna, key)` | `(luna, key) => Runs` | - | Gets, lists, cancels and signals the durable runs of a luna. |
| `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. |

### Events and streams

Details are in [defineEvent](/sdk/define-event) and [stream](/sdk/stream).

| Prop | Type | Default | Description |
| - | - | - | - |
| `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. |
| `streams` | `{ [name]: Stream }` | - | The luna's streams, by the name the luna type gives them. |
| `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. |
| `unsubscribe(id)` | `(id: string) => boolean` | - | Stops following a stream. False if there was no such subscription. |
| `subscriptions()` | `() => SubscriptionInfo[]` | - | The streams this luna follows. |

### Connections

Details are in [Open a connection](/realtime/open-a-connection), [Push to connected apps](/realtime/push-to-connected-apps) and [Connect to an outside WebSocket](/realtime/connect-to-an-outside-websocket).

| Prop | Type | Default | Description |
| - | - | - | - |
| `connection` | `Connection \| undefined` | - | The app connection the call came over, while it is open. |
| `connections` | `{ list(opts?: { tag? }): Connection[]; get(id): Connection \| undefined }` | - | The luna's open app connections. |
| `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. |
| `sockets` | `{ open(url, opts); list(); get(id) }` | - | Outbound WebSockets the luna opened. |

### Files and code

Details are in [bucket](/sdk/bucket), [isolate](/sdk/isolate) and [sandbox](/sdk/sandbox).

| Prop | Type | Default | Description |
| - | - | - | - |
| `blobs` | `{ [name]: Bucket }` | - | The luna's buckets of files. |
| `isolates` | `{ [name]: Isolate }` | - | The luna type's isolate templates, to run JavaScript you did not write. |
| `sandboxes` | `{ [name]: Sandbox }` | - | The luna's sandboxes. |

### The luna's life

| Prop | Type | Default | Description |
| - | - | - | - |
| `sleep()` | `() => void` | - | Called with no argument, puts the luna to sleep once nothing runs on it. |
| `destroy()` | `() => void` | - | Deletes the luna's data, messages and schedules once its running handlers finish. |

### Caller

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

| Prop | Type | Default | Description |
| - | - | - | - |
| `{ 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. |
| `{ luna, key }` | `{ luna: string; key: Record<string, unknown> }` | - | A call or message from a luna, by its type and key. |
| `{ schedule }` | `{ schedule: true }` | - | A schedule or cron fired the call. |
| `{ system }` | `{ system: true }` | - | Luna itself called, such as for a hook. |

### CallOptions

| Prop | Type | Default | Description |
| - | - | - | - |
| `timeout?` | `number \| string` | `"60s"` | How long to wait for the result, in milliseconds or as a duration. |
| `idempotencyKey?` | `string` | - | A retried call with the same key returns the first call's result without running again. |

### SendOptions

| Prop | Type | Default | Description |
| - | - | - | - |
| `delay?` | `number \| string` | - | How long to wait before delivering. |
| `maxAttempts?` | `number` | `10` | How many times to try delivering, at least 1. |
| `firstRetry?` | `number \| string` | `"169s"` | How long to wait before the first retry. |
| `dedupeKey?` | `string` | - | Delivers once, however many messages share this key. |

### ScheduleSpec

Give one of `after`, `at` or `cron`.

| Prop | Type | Default | Description |
| - | - | - | - |
| `handler` | `string` | - | The handler to run. |
| `after?` | `number \| string` | - | Runs once after this delay, such as "10m". |
| `at?` | `Date \| number` | - | Runs once at this time. |
| `cron?` | `string` | - | Runs on this cron schedule. |
| `args?` | `Record<string, unknown>` | `{}` | The handler's arguments. |
| `id?` | `string` | - | The schedule's id. Scheduling again with the same id replaces it. |
| `target?` | `{ luna: Luna \| string; key: Record<string, unknown> }` | `this luna` | Another luna to run the handler on. |
| `tz?` | `string` | `"UTC"` | The time zone a cron is read in. |
| `onMissed?` | `"once" \| "skip" \| "all"` | `"once"` | What a cron does with runs it missed. |
| `overlap?` | `"skip" \| "queue" \| "allow"` | `"skip"` | What a cron does when a run is due while the last one still runs. |

### StepOptions

| Prop | Type | Default | Description |
| - | - | - | - |
| `attempts?` | `number` | `3` | Tries in all for a step that throws an error other than a declared one. |
| `backoff?` | `number` | `1000` | Milliseconds to wait before the first retry, doubling each time. |
| `timeout?` | `number \| string` | - | How long one try may take. A slower try fails and its signal fires. |
| `compensate?` | `(result: T) => unknown` | - | Undoes the step if the run fails or is cancelled later. |

### 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 `await`s 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

```ts luna/lunas/shop.ts
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

```ts luna/lunas/shop.ts
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

```ts luna/lunas/shop.ts
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

```ts luna/lunas/shop.ts
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;
}),
```
