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

isolate

Declare a template for running untrusted JavaScript with limits, and run code in it with ctx.isolates.

isolate declares a template for running JavaScript you did not write, such as a formula or a model’s code, each run in a fresh isolate with its own limits. A handler runs code in it with ctx.isolates.<name>.run.

import { defineLuna, isolate, t, table } from "luna";

export const List = defineLuna({
  name: "List",
  key: { id: t.string() },
  schema: { items: table({ id: t.id(), text: t.string() }) },
  isolates: {
    formula: isolate({ cpu: "100ms", memory: "32MB", timeout: "2s" }),
  },
  handlers: (h) => ({
    evaluate: h({ args: { code: t.string(), input: t.json() } }, async (ctx, { code, input }) => {
      const { result, logs } = await ctx.isolates.formula.run(code, { input });
      return { result, logs };
    }),
  }),
});

Reference

isolate(options)

PropType
cpustring | number

The most CPU time one run may use, such as `"2s"` or milliseconds.

Typestring | number
memory?string

The most memory one run may use, in whole `MB` or `GB`, such as `"256MB"`.

Typestring
Default"64MB"
timeout?string | number

The longest one run may take, waiting included.

Typestring | number
Default"10s"
network?"none" | "public" | { allow: string[] }

What `fetch` reaches: nothing, as the code has no `fetch`, the internet, or only the names listed, such as `"*.github.com"`.

Type"none" | "public" | { allow: string[] }
Default"none"

Isolate.run(code, options)

PropType
codestring

An expression, which is its own result, or the body of an async function, which gives its result with `return`.

Typestring
options.input?unknown

A value the code reads as `input`, passed as JSON.

Typeunknown
options.tools?Record<string, (...args) => unknown>

Functions the code calls as `await tools.<name>(...)`, which run in your luna.

TypeRecord<string, (...args) => unknown>

It returns Promise<IsolateResult<T>>, and throws an IsolateError if the run fails. T is the result’s type, unknown by default.

IsolateResult

PropType
resultT

What the code gave, as JSON.

TypeT
logsIsolateLog[]

What the code logged with `console`.

TypeIsolateLog[]
logsTruncatedboolean

Whether logs past 1 MiB were dropped.

Typeboolean
cpuMsnumber

The CPU time the run used, in milliseconds.

Typenumber

IsolateLog

PropType
level"log" | "info" | "warn" | "error" | "debug"

The `console` method the code called.

Type"log" | "info" | "warn" | "error" | "debug"
messagestring

What it logged.

Typestring

IsolateError

An Error with these fields.

PropType
namestring

The error's name: the code's own, such as `TypeError`, or one of Luna's below.

Typestring
messagestring

What went wrong.

Typestring
logsIsolateLog[]

What the code logged before it failed.

TypeIsolateLog[]
snippetStackstring

The stack trace inside the code.

Typestring
name The run
CpuLimitExceeded Used more CPU time than cpu
MemoryLimitExceeded Used more memory than memory
TimeoutExceeded Took longer than timeout
ResultTooLarge Gave a result larger than 32 MiB
IsolateCrashed Was lost with the process that ran it

Good to know

  • Each run starts fresh. Nothing is kept from one run to the next.
  • A run that a limit stops adds a warning to the luna’s logs, whether or not your code catches the error. Luna writes at most one such line a second for each template and limit.
  • The CPU time of every run counts toward your usage, failed runs included.
  • fetch reaches only http and https. Each redirect must pass network too, and at most 5 are followed.
  • A fetch response body may be as large as memory and at most 16 MiB.
  • A tool that throws makes the code’s await throw, with the same message. Tool names cannot start with __.
  • Stateless luna types can declare isolates too.

Examples

Stop a run that takes too long

safely: h({ args: { code: t.string() } }, async (ctx, { code }) => {
  try {
    return (await ctx.isolates.formula.run<number>(code)).result;
  } catch (e) {
    if (e instanceof IsolateError && e.name === "CpuLimitExceeded") return null;
    throw e;
  }
}),

Import IsolateError from "luna".

Give the code tools

summarise: h({ args: { code: t.string() } }, async (ctx, { code }) => {
  const r = await ctx.isolates.formula.run(code, {
    tools: { items: () => ctx.db.items.find({ orderBy: "id" }).map((i) => i.text) },
  });
  return r.result;
}),

The code calls await tools.items().

Let code call one API

isolates: {
  agent: isolate({ cpu: "2s", network: { allow: ["api.example.com"] } }),
},

Was this page helpful?