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)
cpustring | number
The most CPU time one run may use, such as `"2s"` or milliseconds.
string | numbermemory?string
The most memory one run may use, in whole `MB` or `GB`, such as `"256MB"`.
string"64MB"timeout?string | number
The longest one run may take, waiting included.
string | number"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"`.
"none" | "public" | { allow: string[] }"none"Isolate.run(code, options)
codestring
An expression, which is its own result, or the body of an async function, which gives its result with `return`.
stringoptions.input?unknown
A value the code reads as `input`, passed as JSON.
unknownoptions.tools?Record<string, (...args) => unknown>
Functions the code calls as `await tools.<name>(...)`, which run in your luna.
Record<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
resultT
What the code gave, as JSON.
TlogsIsolateLog[]
What the code logged with `console`.
IsolateLog[]logsTruncatedboolean
Whether logs past 1 MiB were dropped.
booleancpuMsnumber
The CPU time the run used, in milliseconds.
numberIsolateLog
level"log" | "info" | "warn" | "error" | "debug"
The `console` method the code called.
"log" | "info" | "warn" | "error" | "debug"messagestring
What it logged.
stringIsolateError
An Error with these fields.
namestring
The error's name: the code's own, such as `TypeError`, or one of Luna's below.
stringmessagestring
What went wrong.
stringlogsIsolateLog[]
What the code logged before it failed.
IsolateLog[]snippetStackstring
The stack trace inside the code.
stringname |
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.
fetchreaches onlyhttpandhttps. Each redirect must passnetworktoo, and at most 5 are followed.- A
fetchresponse body may be as large asmemoryand at most 16 MiB. - A tool that throws makes the code’s
awaitthrow, 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"] } }),
},