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

sandbox

Declare a Linux sandbox in a luna, and run commands, processes and files in it with ctx.sandboxes.

sandbox declares a Linux machine of the luna’s own under the luna type’s sandboxes option. A handler drives it as ctx.sandboxes.<name>, and it starts on first use.

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

export const User = defineLuna({
  name: "User",
  key: { id: t.string() },
  sandboxes: {
    dev: sandbox({ image: "ghcr.io/acme/tools@sha256:<DIGEST>", memory: "1GB" }),
  },
  handlers: (h) => ({
    test: h({}, async (ctx) => {
      const r = await ctx.sandboxes.dev.exec("npm test", { cwd: "/home/app" });
      return { ok: r.exitCode === 0, out: r.stdout };
    }),
  }),
});

Reference

sandbox(options)

PropType
imagestring

An OCI image pinned by digest, such as `ghcr.io/acme/tools@sha256:…`, and when the digest names an index, the build for the machine's architecture is used.

Typestring
cpu?number | { max: number; default?: number }

Virtual CPUs, and with `max`, each instance starts with `default` and can be resized from 1 to `max`.

Typenumber | { max: number; default?: number }
Default1
memory?string | { max: string; default?: string }

Memory as `"512MB"` or `"2GB"`, and with `max`, each instance starts with `default` and can be resized from `"256MB"` to `max`.

Typestring | { max: string; default?: string }
Default"512MB"
disk?string

The size of `/home`, and of the writable layer over the image.

Typestring
Default"4GB"
idle?string | number

Powers it off after this long with no request.

Typestring | number
Default"5m"
persist?"none" | "filesystem" | "freeze"

What is kept when it stops: nothing, its disks, or its disks with its memory and processes where that can be done.

Type"none" | "filesystem" | "freeze"
Default"filesystem"
network?"none" | "public" | { allow: string[] }

What it can reach: nothing, as it has no network device, the internet, or only the names listed, such as `"*.github.com"`.

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

Puts it on a network with this luna's other such sandboxes, as `<name>.sandbox.internal`.

Typeboolean
Defaultfalse
ports?number[]

The ports the luna reaches with `port(n)`.

Typenumber[]

Sizes take MB, GB or TB, such as "1.5GB".

Sandbox

PropType
namestring

The instance's name.

Typestring
filesSandboxFiles

The files of its `/home` volume.

TypeSandboxFiles
exec(command, opts?)Promise<ExecResult>

Runs a command and waits for it, where a string goes to `/bin/sh -c` and an array runs as it is.

TypePromise<ExecResult>
spawn(command?, opts?)Promise<SandboxProcess>

Starts a process that runs on after this call, and with no command, a login shell.

TypePromise<SandboxProcess>
attach(name)SandboxProcess

A process started before, by its name.

TypeSandboxProcess
processes()Promise<ProcessInfo[]>

Its processes: those running, and those that ended whose output is kept.

TypePromise<ProcessInfo[]>
port(n)SandboxPort

A declared port, to send HTTP requests to or hand to an app.

TypeSandboxPort
terminal(opts?)Promise<SandboxTicket>

A ticket for an app to connect to a process as a terminal, over a WebSocket.

TypePromise<SandboxTicket>
ssh()Promise<SandboxSsh>

How to reach it over SSH, which the luna's `onSshConnect` hook allows.

TypePromise<SandboxSsh>
status()Promise<SandboxStatus>

Its state, size and last use, without starting it.

TypePromise<SandboxStatus>
list()Promise<SandboxStatus[]>

Every instance of this declaration the luna has.

TypePromise<SandboxStatus[]>
instance(name, size?)Sandbox

Another instance of this declaration, which starts on first use with `size` if it is new.

TypeSandbox
fork(name)Promise<Sandbox>

A new instance with a copy of this one's disks as they are now.

TypePromise<Sandbox>
resize(size)Promise<{ cpu: number; memoryMib: number }>

Sets its size, at once if it runs or for its next start, for a resizable declaration.

TypePromise<{ cpu: number; memoryMib: number }>
stop()Promise<void>

Powers it off now, keeping what `persist` says.

TypePromise<void>
freeze()Promise<void>

Saves its memory and processes with its disks, so the next use carries on from there.

TypePromise<void>
destroy()Promise<void>

Deletes it and everything kept of it.

TypePromise<void>

SandboxPort

PropType
portnumber

The port.

Typenumber
fetch(path, init?)Promise<Response>

Sends an HTTP request with `method`, `headers`, `body` and `timeout`, wakes the sandbox for it, and returns up to 16 MiB.

TypePromise<Response>
connect()Promise<SandboxTicket>

A ticket for an app to reach the port over a WebSocket whose binary messages are the bytes each way.

TypePromise<SandboxTicket>
publicUrl()Promise<string>

A public HTTPS address for the port while the sandbox runs, the same every time, where your plan allows it.

TypePromise<string>
revokePublicUrl()Promise<void>

Takes the public address down.

TypePromise<void>

A port works whether or not the sandbox has a network.

SandboxFiles

Paths are relative to /home, or absolute within it.

PropType
read(path, opts?)Promise<Uint8Array>

A file's bytes, from `opts.offset` for `opts.length` bytes.

TypePromise<Uint8Array>
text(path)Promise<string>

A file as UTF-8 text.

TypePromise<string>
write(path, data, opts?)Promise<number>

Writes a file with any directories it needs, with `opts.mode`, and returns its size.

TypePromise<number>
list(path?)Promise<FileInfo[]>

The entries of a directory, `"."` by default.

TypePromise<FileInfo[]>
stat(path)Promise<FileInfo | null>

What is at `path`, or `null`.

TypePromise<FileInfo | null>
remove(path, opts?)Promise<boolean>

Removes a file, or a directory with `opts.recursive`, and says whether there was one.

TypePromise<boolean>
mkdir(path)Promise<void>

Makes a directory.

TypePromise<void>
copyTo(bucket, from, to?, opts?)Promise<void>

Copies a file of up to 256 MiB to a bucket, with `opts.contentType`.

TypePromise<void>
copyFrom(bucket, from, to?)Promise<void>

Copies an object from a bucket into the volume, waking the sandbox.

TypePromise<void>

SandboxProcess

PropType
namestring

The process's name in its sandbox.

Typestring
at{ stdout: number; stderr: number }

How far its output has been read, which you may set to read again from there.

Type{ stdout: number; stderr: number }
read(opts?)Promise<ProcessOutput>

What it wrote since the last read, waiting up to `opts.wait` and at most a minute, `opts.max` bytes at most.

TypePromise<ProcessOutput>
text(opts?)Promise<{ stdout: string; stderr: string; lost: number; exit: ProcessExit | null }>

`read`, as text.

TypePromise<{ stdout: string; stderr: string; lost: number; exit: ProcessExit | null }>
write(data)Promise<void>

Writes to its input.

TypePromise<void>
end()Promise<void>

Closes its input.

TypePromise<void>
resize(cols, rows)Promise<void>

Sets its terminal's size.

TypePromise<void>
kill(signal?)Promise<void>

Sends it and everything it started a signal, `"TERM"` by default.

TypePromise<void>
wait(timeout?)Promise<ProcessExit | null>

How it ended, waiting up to `timeout`, `"1m"` by default and at most, and `null` if it still runs.

TypePromise<ProcessExit | null>
remove()Promise<void>

Ends it if it runs, and forgets it and its output.

TypePromise<void>

ExecOptions and ExecResult

PropType
cwd?string

The working directory.

Typestring
Default"/home"
env?Record<string, string>

Environment variables.

TypeRecord<string, string>
timeout?string | number

Stops the command and everything it started after this long.

Typestring | number
Default"5m"
stdin?string | Uint8Array

Written to its standard input.

Typestring | Uint8Array

exec returns an ExecResult.

PropType
exitCodenumber | null

Its exit code, or `null` if a signal ended it.

Typenumber | null
stdoutstring

Its standard output.

Typestring
stderrstring

Its standard error.

Typestring
timedOutboolean

Whether `timeout` stopped it.

Typeboolean
truncatedboolean

Whether output past 16 MiB on either stream was dropped.

Typeboolean

SpawnOptions

PropType
name?string

A name to `attach` by, unique in the sandbox, of letters, digits, `-`, `_` and `.`, and without one it gets a name of its own.

Typestring
pty?boolean | { cols: number; rows: number }

Runs it on a terminal, 80 by 24 for `true`, with its output and errors together.

Typeboolean | { cols: number; rows: number }
cwd?string

The working directory.

Typestring
Default"/home"
env?Record<string, string>

Environment variables.

TypeRecord<string, string>
user?string

A user of the image to run as.

Typestring
Defaultroot
keepAwake?boolean

Keeps the sandbox, and its luna, awake while it runs.

Typeboolean
Defaultfalse
buffer?string

How much of its output is kept to read back, at most `"64MB"`.

Typestring
Default"1MB"

TerminalOptions

TerminalOptions takes cwd, env, user, keepAwake and buffer as in SpawnOptions, and these.

PropType
name?string

The process to join, started first if it does not run, and kept when the connection goes, while one with no name ends with its connection.

Typestring
command?string | string[]

What to start, a login shell by default.

Typestring | string[]
pty?boolean | { cols: number; rows: number }

Its terminal's size to begin with, or `false` for none.

Typeboolean | { cols: number; rows: number }
Default80 by 24
replay?number

How many bytes of what a named process wrote before are sent first, all that is kept by default.

Typenumber

SandboxTicket and SandboxSsh

PropType
pathstring

The path to open as a WebSocket on your app's URL, such as `/_luna/sandbox/connect?ticket=…`.

Typestring
ticketstring

The ticket.

Typestring
expiresMsnumber

When it stops working, a minute after it was made, in milliseconds since the epoch.

Typenumber

A ticket works once. ssh() returns a SandboxSsh.

PropType
hoststring

The host to connect to.

Typestring
portnumber

The port to connect to.

Typenumber
userstring

The SSH login name, which names this sandbox and is the same every time.

Typestring
hostKeystring

The host key, as `ssh-ed25519 AAAA…`, for a `known_hosts` line of `[host]:port` and this.

Typestring
commandstring

The command to connect, `ssh -p <port> <user>@<host>`.

Typestring

SandboxStatus and SandboxSize

PropType
namestring

The instance's name.

Typestring
state"running" | "asleep" | "frozen" | "none"

Running, stopped with its disks, stopped with its memory and processes too, or no such sandbox.

Type"running" | "asleep" | "frozen" | "none"
cpunumber

The CPUs it has, or will start with.

Typenumber
memoryMibnumber

The memory it has, or will start with, in MiB.

Typenumber
max?{ cpu: number; memoryMib: number }

The most it can be resized to, for a resizable declaration.

Type{ cpu: number; memoryMib: number }
createdMs?number

When it was made.

Typenumber
lastUsedMs?number

When it was last used.

Typenumber
diskUsedBytes?number

What its disks hold.

Typenumber
startedMs?number

When it started, while it runs.

Typenumber
connections?number

The connections open to it, while it runs.

Typenumber
stoppedBy?"idle" | "code" | "luna" | "crash"

Why it last stopped: no use, its luna's code, its luna sleeping or moving, or it ended by itself.

Type"idle" | "code" | "luna" | "crash"
stoppedMs?number

When it last stopped.

Typenumber

Times are milliseconds since the epoch. A SandboxSize is { cpu?: number; memory?: string }, with memory as "2GB".

ProcessInfo, ProcessOutput and ProcessExit

PropType
namestring

Its name.

Typestring
pidnumber

Its process id.

Typenumber
ptyboolean

Whether it runs on a terminal.

Typeboolean
commandstring

What it runs.

Typestring
startedMsnumber

When it started, in milliseconds since the epoch.

Typenumber
keepAwakeboolean

Whether it keeps the sandbox awake.

Typeboolean
runningboolean

Whether it still runs.

Typeboolean
exitProcessExit | null

How it ended.

TypeProcessExit | null
stdoutnumber

How many bytes it wrote to standard output.

Typenumber
stderrnumber

How many bytes it wrote to standard error.

Typenumber

read returns a ProcessOutput.

PropType
stdoutUint8Array

Standard output since the last read.

TypeUint8Array
stderrUint8Array

Standard error since the last read.

TypeUint8Array
lostnumber

Bytes written before these that are no longer kept, because its buffer was full.

Typenumber
exitProcessExit | null

How it ended, once all it wrote has been read.

TypeProcessExit | null

A ProcessExit is { exitCode: number | null; signal: number | null }: its exit code, or the signal that ended it.

FileInfo

PropType
namestring

The entry's name.

Typestring
type"file" | "dir" | "symlink"

What it is.

Type"file" | "dir" | "symlink"
sizenumber

Its size in bytes.

Typenumber
modenumber

Its permission bits.

Typenumber
mtimeMsnumber

When it last changed, in milliseconds since the epoch.

Typenumber

Good to know

  • An image with a tag and no digest is refused when the luna type is defined. An image unpacks to at most 32 GiB.
  • A process does not keep an idle sandbox running unless it was spawned with keepAwake.
  • A named process runs until it ends or is killed, and its output stays readable after.
  • A command that must outlive the call runs with spawn, and later calls read it with attach.
  • Reading its files works while the sandbox is asleep.
  • resize is refused when the sandbox uses more memory than it would be left with. A sandbox is billed at the size it is set to.
  • Private addresses are never reachable from a sandbox. internet: false on the luna type also turns the internet off for its sandboxes.
  • A request for more CPU, memory or disk than Luna allows is refused. Your plan also caps how many sandboxes run at once. See Limits.

Examples

Run a dev server and read its output

serve: h({}, async (ctx) => {
  const p = await ctx.sandboxes.dev.spawn("npm run dev", { name: "server", cwd: "/home/app", keepAwake: true });
  return p.name;
}),
logs: h({}, async (ctx) => {
  const out = await ctx.sandboxes.dev.attach("server").text({ wait: "5s" });
  return { text: out.stdout, lost: out.lost, exit: out.exit };
}),

Write and read files

files: h({}, async (ctx) => {
  const files = ctx.sandboxes.dev.files;
  await files.write("app/notes.txt", "hello");
  const list = await files.list("app");
  return { text: await files.text("app/notes.txt"), names: list.map((f) => f.name) };
}),

Make a sandbox resizable

sandboxes: {
  dev: sandbox({
    image: "ghcr.io/acme/tools@sha256:<DIGEST>",
    cpu: { max: 4 },
    memory: { max: "8GB", default: "1GB" },
    disk: "10GB",
    network: "public",
    ports: [3000],
  }),
},
grow: h({}, async (ctx) => ctx.sandboxes.dev.resize({ cpu: 4, memory: "8GB" })),

Call a server in the sandbox

health: h({}, async (ctx) => (await ctx.sandboxes.dev.port(3000).fetch("/health")).status),

Hand an app a terminal

shell: h({}, async (ctx) => ctx.sandboxes.dev.terminal({ name: "shell", cwd: "/home/app" })),

The app opens the ticket’s path on your app’s URL as a WebSocket within a minute.

Try a change on a copy

branch: h({ args: { name: t.string() } }, async (ctx, { name }) => {
  const copy = await ctx.sandboxes.dev.fork(name);
  return (await copy.exec(["git", "status"])).stdout;
}),

Was this page helpful?