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

tenants

Create, deploy, configure, copy and delete the tenants of an environment from a luna's handler.

tenants returns a client for the tenants added to an environment. A platform’s lunas use it to give each customer a tenant and deploy the customer’s code to it.

import { defineLuna, t, tenants } from "luna";

export const Customer = defineLuna({
  name: "Customer",
  key: { id: t.string() },
  handlers: (h) => ({
    open: h({ args: { name: t.string() } }, async (ctx, { name }) => {
      const platform = tenants({ token: ctx.env.PLATFORM_TOKEN, parent: ctx.tenant });
      const made = await platform.create(name, { labels: { plan: "free" } });
      return made.tenant;
    }),
  }),
});

Reference

tenants(options)

PropType
tokenstring

An API token with the scopes each method needs.

Typestring
parentstring

The full name of the environment's default tenant, which the tenants belong to.

Typestring

Call it inside a handler. It reaches Luna from there with no network. In a luna of the default tenant, ctx.tenant holds the name parent needs. luna tenants list --json shows it as the tenant of the default row.

TenantsClient

Methods take a tenant’s short name, the one you passed to create.

PropType
create(name, options?)Promise<{ tenant: string; publishableKey: string; apiToken: string }>

Adds a tenant, with `options.labels` to find it by, and returns its full name and its two main credentials.

TypePromise<{ tenant: string; publishableKey: string; apiToken: string }>
list(options?)Promise<{ tenants: { name: string; version: number; labels?: Record<string, string> }[]; cursor: string | null }>

The environment's tenants in order of name, only those with every label in `options.labels`, `options.limit` at a time, after the `options.after` cursor.

TypePromise<{ tenants: { name: string; version: number; labels?: Record<string, string> }[]; cursor: string | null }>
get(name)Promise<unknown>

The tenant: its version, settings, the limits that hold for it, its usage counters and its luna types.

TypePromise<unknown>
deploy(name, code)Promise<TenantDeployResult>

Builds source files and deploys them to the tenant.

TypePromise<TenantDeployResult>
configure(name, settings)Promise<void>

Changes the settings in `settings` and keeps the rest.

TypePromise<void>
fork(name, to, options?)Promise<{ copied: number; skipped: number }>

Copies every luna of a tenant into another, as they are now or at `options.at`.

TypePromise<{ copied: number; skipped: number }>
delete(name)Promise<{ deleted: boolean }>

Deletes the tenant with its lunas, data, versions, keys and secrets.

TypePromise<{ deleted: boolean }>

Each scope the token needs:

Method Scope
create, deploy, configure, delete tenants:write
list, get None: any token that reaches the environment
fork data:read on the source and data:write on the destination

deploy code

PropType
filesRecord<string, string>

Each file's relative path, split by `/`, and its contents as UTF-8 text.

TypeRecord<string, string>
entry?string

The entry module's path, and when left out, Luna reads the config file or looks for a default entry module.

Typestring
confirm?boolean

Deploys even though the preview lists changes that need your say-so.

Typeboolean
Defaultfalse

TenantDeployResult

PropType
deployedboolean

Whether the files were deployed.

Typeboolean
version?number

The version the tenant now runs.

Typenumber
previewunknown

What the deploy changes, or what blocked it.

Typeunknown
publishableKey?string

The tenant's main publishable key.

Typestring
apiToken?string

The tenant's main secret token.

Typestring

configure settings

The type of settings is TenantLimits, which the package exports.

PropType
quotas.requestsPerSecond?number

The most requests a second.

Typenumber
quotas.cpuPercent?number

The most CPU the tenant can use, as a percent of one core.

Typenumber
quotas.storageBytes?number

The most storage, in bytes.

Typenumber
quotas.sandboxes?number

The most sandboxes running at once.

Typenumber
quotas.lunaMemoryMib?number

The most memory one luna can declare or use, in MiB.

Typenumber
quotas.lunaCpu?number

The most cores one luna can declare or use.

Typenumber
quotas.lunaDefaultMemoryMib?number

The memory a luna has when it declares none, in MiB.

Typenumber
quotas.lunaDefaultCpu?number

The cores a luna has when it declares none.

Typenumber
hostnames?string[]

Extra routes to the tenant, each as `host` or `host/first-path-segment`.

Typestring[]
grants?Record<string, { luna: string }>

The platform's luna types the tenant's code may call, each under the service name its code uses.

TypeRecord<string, { luna: string }>
outbound?{ luna: string; key: unknown; handler: string } | null

A handler of the platform's that sees each request the tenant sends out and may refuse it.

Type{ luna: string; key: unknown; handler: string } | null
retentionDays?number

Days the tenant's logs and traces are kept.

Typenumber
historyDays?number

Days back its lunas can be restored or forked, at most what the plan keeps.

Typenumber
otlp?{ endpoint: string; headers?: Record<string, string> } | null

A separate export of the tenant's telemetry.

Type{ endpoint: string; headers?: Record<string, string> } | null
labels?Record<string, string>

Tags for finding and grouping tenants.

TypeRecord<string, string>

The outbound handler receives { tenant, method, url, host, port } and answers { allow: boolean }. Any other answer, or none within 5 seconds, refuses the request.

fork options

PropType
at?number

The moment to copy the lunas as of, in milliseconds since the epoch, and now when left out.

Typenumber
schedules?boolean

Whether each copy keeps its source's schedules.

Typeboolean
Defaultfalse

Good to know

  • A tenant’s name is lower-case letters, digits and single dashes. With its parent’s name it fits in 60 characters, and no tenant is named default.
  • A tenant has its own lunas, data, keys and secrets. It runs nothing until you deploy to it.
  • The files of one deploy are at most 48 MiB, paths included. Luna builds them inside the tenant’s own isolation.
  • A refused deploy returns deployed: false with its preview. It does not throw.
  • Any other failure throws an Error with the message Luna answered.
  • list returns full names, and includes the environment’s default tenant.
  • fork copies one page of lunas per request and goes on until all are copied. A destination with nothing deployed gets the source’s code and settings first.
  • delete returns deleted: false while the delete carries on in the background.
  • configure keeps every setting you leave out. A setting you pass is replaced whole, so quotas replaces every quota.

Examples

Deploy a customer’s code

ship: h({ args: { name: t.string(), code: t.string() } }, async (ctx, { name, code }) => {
  const platform = tenants({ token: ctx.env.PLATFORM_TOKEN, parent: ctx.tenant });
  const result = await platform.deploy(name, { files: { "lunas.ts": code }, entry: "lunas.ts" });
  if (!result.deployed) return { refused: result.preview };
  return { version: result.version };
}),

Set a tenant’s limits and routes

limit: h({ args: { name: t.string() } }, async (ctx, { name }) => {
  const platform = tenants({ token: ctx.env.PLATFORM_TOKEN, parent: ctx.tenant });
  await platform.configure(name, {
    quotas: { requestsPerSecond: 50, sandboxes: 2 },
    hostnames: [`${name}.example.com`],
    grants: { billing: { luna: "Billing" } },
  });
}),

List tenants by label

free: h({}, async (ctx) => {
  const platform = tenants({ token: ctx.env.PLATFORM_TOKEN, parent: ctx.tenant });
  let page = await platform.list({ labels: { plan: "free" }, limit: 100 });
  const names = page.tenants.map((x) => x.name);
  while (page.cursor) {
    page = await platform.list({ labels: { plan: "free" }, limit: 100, after: page.cursor });
    names.push(...page.tenants.map((x) => x.name));
  }
  return names;
}),

Copy a tenant as it was an hour ago

copy: h({ args: { from: t.string(), to: t.string() } }, async (ctx, { from, to }) => {
  const platform = tenants({ token: ctx.env.PLATFORM_TOKEN, parent: ctx.tenant });
  return platform.fork(from, to, { at: ctx.now() - 3_600_000 });
}),

Keep the token as a secret named PLATFORM_TOKEN, set with luna secrets. See Automate with API tokens.

Was this page helpful?