# API reference

https://virtx.sh/docs/reference/api/

Every call the Python, Node.js, and Rust clients make, grouped by what it acts on, and the environment variables they read.

Names here are Python's.
Node.js uses the same names in camelCase, such as `createSandbox` for `create_sandbox`, and Rust uses the same names as Python, except where noted.

What a call returns, once awaited where it is async, is named as Python has it.
The types share their names in all three: `list[Sandbox]` is `Sandbox[]` in Node.js, inside a `Promise`, and `Vec<Sandbox>` in Rust, inside a `Result`.

A call that starts a job, marked **job** below, is completed with `complete` for how it ended, iterated for its log, or awaited for the job; see [Follow a job](https://virtx.sh/docs/guides/running-commands/#follow-a-job) in Running commands.
In Rust, `complete` is the job's, after awaiting the call.
Its log, like a job's `log`, yields a `LogEntry` at a time.
`download_image` and `upload_image` yield `Progress` events, then one event carrying their output.

## Client

| Call | Returns | What it does |
| --- | --- | --- |
| `Client.spawn(program, args)` | `Client` | Starts a server as a child process and talks to it over its stdin and stdout. Without `program`, it starts `virtx-stdio` of the library's version, fetched into a cache the first time. Rust calls the no-program form `Client::spawn_virtx`. |
| `Client.connect(url, auth, project, headers)` | `Client` | Reaches a server over HTTP at its base `url`, sending `auth` and `headers` with every request, every request in `project`. A token is sent over plain `http` only to this machine's loopback. |
| `set_auth(auth)`, `set_headers(headers)`, `set_project(project)` | `None` | Replace what every later request sends. Without a project, a request is in its user's own, `default`. |
| `clone()` | `Client` | Another hold of the same session. |
| `close()` | `None` | Lets go of this hold; the last one ends the session. Python's `aclose` does it off the event loop. |
| `ensure_virtx()` | `str`, its path | Fetches `virtx-stdio` into the cache ahead of `spawn`, without starting it. Node.js calls it `ensureVirtx`. |

## Projects

Everything on a server belongs to a project, which a client names at `connect`, or with `set_project`: a project of the user's by its name, or any by its id.
See [Managing projects](https://virtx.sh/docs/guides/projects/), and [Projects](https://virtx.sh/docs/reference/protocol/#projects) in the protocol.

| Call | Returns | What it does |
| --- | --- | --- |
| `create_project(name)` | `Project` | Makes a project, its maker its owner. |
| `list_project()`, `get_project(name)` | `list[Project]`, `Project` | The projects the client has a role in; `get_project` takes a name of the user's or an id. |

A `Project` has its `id`, its `name`, its `owner` (none for one made over stdio) and the client's `role` in it, `owner` or `member`.
Over stdio it has no members, and the calls on them are refused with `404`:

| Call | Returns | What it does |
| --- | --- | --- |
| `members()` | `list[ProjectMemberListOutputItem]` | Its members, each a `user` and a `role`. |
| `set_member(user, role)` | `ProjectMemberListOutputItem` | Gives `user` the role, adding them if they are no member: an owner's to do. |
| `remove_member(user)` | `None` | Takes `user`'s role away: an owner's to do, or the user's own, leaving it. |
| `remove()` | `None` | Deletes it and everything in it: an owner's to do, refused with `409` while a sandbox lives in it. |

## Images

See [Working with images](https://virtx.sh/docs/guides/images/).

| Call | Returns | What it does |
| --- | --- | --- |
| `build_image(recipe, reference)` | `ImageJob` | **Job.** Builds `recipe` and points `reference` at the result. |
| `pull_image(reference, auth)` | `ImageJob` | **Job.** Pulls `reference` from its registry. Without `auth`, anonymously. |
| `push_image(reference, auth)` | `ImageJob` | **Job.** Pushes the image `reference` points at to the registry it names. |
| `list_image()` | `list[ImageListOutputItem]` | Every tag on the server's images, with the digest it points at. |
| `tag_image(source, target)` | `None` | Points the tag `target` at the image `source` names, moving it if it is in use. |
| `untag_image(reference)` | `None` | Removes a tag, leaving the image; refused for the last tag of an image a sandbox or a build uses. |
| `remove_image(reference)` | `None` | Removes the image and every tag on it in that name; refused, with nothing removed, while a sandbox or a build uses it. |
| `download_image(reference, path)` | events, then `ImageDownloadOutput` | Writes the image to an OCI image layout tar archive at `path`. |
| `upload_image(path, reference)` | events, then `ImageUploadOutput` | Uploads the image in an OCI archive and points the tag `reference` at it. |
| `prune_image()` | `ImagePruneOutput` | Deletes images no tag points at and no sandbox uses, once they are an hour old. |

A `Recipe(base)` is chained with `.run(command)`, `.env(key, value)` and `.workdir(directory)`.
In Rust, `Recipe::new(base).step(..)` takes a `Step::run`, `Step::env` or `Step::workdir`, or a plain string as a `run` step, and `Recipe::from_dockerfile(text)` reads a Dockerfile.

## Sandboxes

See [Setting up sandboxes](https://virtx.sh/docs/guides/setting-sandboxes/) for the options `create_sandbox` takes.

| Call | Returns | What it does |
| --- | --- | --- |
| `create_sandbox(image, ...)` | `Sandbox` | Makes a sandbox of `image`, with the options given. `image` has to be on the server already, pulled or built: this does not pull it. |
| `list_sandbox()`, `get_sandbox(id)` | `list[Sandbox]`, `Sandbox` | The server's sandboxes, each port without its `url`. |
| `find_sandbox(name)` | `Sandbox` or none | The sandbox made with `name`, each port without its `url`; none if no sandbox has it. |

A `Sandbox` carries its client, and acts on itself:

| Call | Returns | What it does |
| --- | --- | --- |
| `exec(cmd, stdin, timeout_ms)` | `SandboxJob` | **Job.** Runs `cmd`, an argv. With `stdin`, its stdin stays open for `write_stdin`; with `timeout_ms`, it is killed when the time runs out. Iterated before it is awaited, the job is started and its log read as one request where the server answers so. In Rust, `exec_with_log(args)` yields the job, then its log. |
| `jobs()`, `job(id)` | `list[SandboxJob]`, `SandboxJob` | Its jobs. |
| `resize(vcpus, memory_mib, disk_gib)` | `SandboxResources` | Its vCPUs and memory from its VM's next boot on, its VM stopped now if nothing uses it and refused `409` if something does; its disk grown, never shrunk, at its VM's next boot, stopping nothing. Answers `vcpus`, `memory_mib`, `disk_gib` and `up`, whether its VM is up now. See [Resize a sandbox](https://virtx.sh/docs/guides/setting-sandboxes/#resize-a-sandbox). |
| `remove()` | `None` | Stops it, ends its jobs, and forgets it, with everything it wrote outside its volumes. |

Its [files](#files) are as its processes see them.

In Rust, `Sandbox` answers `id()`, `name()` and `info()`, which holds its `image`, `running` and `ports`, and `resize` takes a `SandboxResizeArgs`, chained from `SandboxResizeArgs::default()`.

A port in `create_sandbox`'s `ports` is a number, for TCP, or a `PortSpec(port, label, protocol, inbound)`; in Node.js, `{ port, label?, protocol?, inbound? }`.
Each comes back as a `SandboxPort`: its `port` and `url`, its `label` and `protocol` as given, an `address` where the server gives a TCP port one, and an `inbound_error` where it opened one whose rules it could not set.
`list_sandbox` and `get_sandbox` answer each port with its `port`, `label`, `protocol` and `address`, and no `url`: `create_sandbox` alone answers that, since it carries the port's credentials. A `protocol` this version does not know is kept as the server's string: a `str` in Python, `PortProtocol::Other` in Rust.
An `InboundRule(source, description)` lets in `source`, an IPv4 or IPv6 CIDR or one address; a server that keeps no rules, as `virtx-stdio` and `virtx-server-tcp` do not, refuses `inbound` with `400`.

A sandbox a server kept across its restart but could not know again, such as one whose image is gone, is listed with `running` false and an `error` saying why; it takes nothing but `remove`.

## Jobs

A job is a sandbox's process, from `exec`, or an image's build, pull or push.

### Sandbox jobs

A `SandboxJob`, from awaiting `exec` or from `job(id)`, has its `id`, `pid`, `cmd`, whether it is `running`, and once it has ended, its exit `code` and, if it did not end by itself, the `reason`: `timeout`, `cancelled`, `sandbox_deleted`, `vm_exited` or `oom`, as [Set a timeout](https://virtx.sh/docs/guides/running-commands/#set-a-timeout) in Running commands says, or `restarted`, for one that ran when its server restarted, keeping its sandbox. A reason this version does not know is kept as the server's string: a `str` in Python, `SandboxJobEndReason::Other` in Rust.

| Call | Returns | What it does |
| --- | --- | --- |
| `get()` | `SandboxJob` | The job as the server has it now. |
| `complete(print)` | `int` | Follows it to its end, printing its output if `print`, and answers its exit code. |
| `log(after)` | a `LogEntry` at a time | Its output, from its start or after entry `after`, until its end. An entry of a kind this version does not know is passed over in Python and Node, and is `SandboxJobEntry::Other` in Rust, which `complete` passes over. |
| `signal(signal)` | `None` | Sends a signal, such as `"SIGTERM"`, to its process and every process it started. |
| `write_stdin(data, eof)` | `None` | Writes to the stdin of a job started with `stdin`, and closes it if `eof`. Await each write before the next. A write its process closed its stdin under part-way raises `409`, `ended`, its `written` how many bytes went in. One the server has no room for yet, after writes given up on while the process did not read, is turned away for now as `503` `capacity`, nothing of it taken, and, if its request is at most 1 MiB, sent again as below. |
| `remove()` | `None` | Kills its process if it runs, and forgets the job. |

Code that holds only ids gets the job back with `get_sandbox(id)`, then its `job(id)`.
In Rust, `SandboxJob` answers `id()` and `info()`.

### Image jobs

| Call | Returns | What it does |
| --- | --- | --- |
| `list_image_job()`, `get_image_job(id)` | `list[ImageJob]`, `ImageJob` | The server's image jobs. |

An `ImageJob`, from awaiting `build_image`, `pull_image` or `push_image` or from `get_image_job(id)`, carries its client and acts on itself.
It has its `id`, its `kind`, the `reference` it points or pushes, whether it is `running`, and once it has ended, the `digest` it made or the `error` it failed with.

| Call | Returns | What it does |
| --- | --- | --- |
| `get()` | `ImageJob` | The job as the server has it now. |
| `complete(print)` | `str` | Follows it to its end, printing its log if `print`, and answers the digest it made. Raises the error it failed with. |
| `log(after)` | a `LogEntry` at a time | Its log, from its start or after entry `after`, until its end, or the error it failed with in place of its end. An entry of a kind this version does not know is passed over in Python and Node, and is `ImageJobEntry::Other` in Rust, which `complete` passes over. |
| `remove()` | `None` | Cancels it if it runs, and forgets the job. |

In Rust, `ImageJob` answers `id()` and `info()`.

## Errors

A call that fails raises a `VirtxError`, thrown in Node.js and an `Error` in Rust.
Its `source` says where it failed, and `status` the HTTP status when the server refused the request:

| `source` | `status` | When |
| --- | --- | --- |
| `server` | the HTTP status | The server refused the request, such as `404` for what does not exist and `409` for what is in use. |
| `job` | none | The job the call started failed, such as a build whose step exited nonzero. |
| `transport` | none | The request or its answer did not get through: the connection failed or the session ended. |
| `client` | none | This side failed: an argument, a file on this machine, or an answer it could not read. |

Where the server answered its refusal as the protocol does, `code` is the protocol's code for it, such as `not_found` or `in_use`, and otherwise none.
Tell errors apart by `source`, `status` and `code`, not by the message.
A write to a job's stdin that its process closed the stdin under part-way also has `written`, how many bytes of it went in; every other error has none.
In Rust, `source_kind()` answers the `Source`, `status()` the status, `code()` the code and `written()` that count.

A request the server turns away for now, such as `503` `capacity` while it has no room for a sandbox, is sent again after the wait the server asks for, for up to 30 seconds, before the call fails with it. Only a request whose body is at most 1 MiB is sent again; a larger one fails with the first refusal.
A `429` `quota` for a limit that frees up only as you close or delete something, such as the sandboxes you have, fails at once.

## Volumes

See [Mounting volumes](https://virtx.sh/docs/guides/mounting-volumes/).

| Call | Returns | What it does |
| --- | --- | --- |
| `create_volume(name)` | `Volume` | Makes an empty volume. Without a name, the server picks one. |
| `list_volume()`, `get_volume(name)` | `list[Volume]`, `Volume` | The server's volumes. |

A `Volume` has its `name` and `size`, and its [files](#files):

| Call | Returns | What it does |
| --- | --- | --- |
| `mount(path, source)` | `VolumeMountListOutputItem` | Mounts a remote store at `path` in it, read-only. |
| `mounts()` | `list[VolumeMountListOutputItem]` | The mounts in it, without their credentials. |
| `unmount(path)` | `None` | Takes a mount away, leaving its store as it is. |
| `remove()` | `None` | Deletes it and everything in it. |

## Files

A `Sandbox` and a `Volume` share these calls, each on its own files, by a path relative to its root such as `dir/file.txt`.

| Call | Returns | What it does |
| --- | --- | --- |
| `stat_file(path)` | `Metadata` | What is at `path`: its size, its modification time, and its `etag`. |
| `exists(path)`, `is_file(path)`, `is_dir(path)` | `bool` | Whether anything, a file, or a directory is at `path`. |
| `read_dir(path)` | `list[DirEntry]` | The entries of a directory, each with its `name` and `metadata`. |
| `read_file(path, offset, length)` | `bytes` | A file's bytes, all of them or a range. |
| `read_text(path)` | `str` | A whole UTF-8 file as text. |
| `write_file(path, content, if_match)` | `None` | Writes a whole file, whose parent directory must exist. With `if_match`, only while the file still has that `etag`. |
| `create_dir(path)` | `None` | Creates a directory whose parent exists. |
| `create_dir_all(path)` | `None` | Creates a directory and its parents, as `mkdir -p`. |
| `remove_file(path, missing_ok)` | `None` | Removes a file, or a directory with everything in it. With `missing_ok`, nothing being there is fine. |
| `rename_file(from_path, to_path, overwrite)` | `None` | Moves a file or directory; refused onto something that exists unless `overwrite`. |
| `copy_file(from_path, to_path, overwrite)` | `None` | Copies a file or directory, as `rename_file` replaces. |

## PortForwarder

See [Networks and ports](https://virtx.sh/docs/guides/networks-ports/).

| Call | Returns | What it does |
| --- | --- | --- |
| `PortForwarder.open(client, port)` | `PortForwarder` | Forwards a sandbox's port, as `ports` answers it, or the `url` answered for it, to an address on this machine's loopback. Given the port, a failed connection's error names its number. |
| `last_error` | `VirtxError` or `None` | Why the last connection that failed did -- its WebSocket refused, or closed before the port sent a byte, with the server's reason if it gave one -- naming the port; `None` again once a later connection's port sends a byte. Each failure is also logged as a warning. In Node, `lastError`; in Rust, `last_error()`. |
| `address`, `host`, `port` | `str`, `str`, `int` | Where it is reached. In Rust, `address()`. |
| `close()` | `None` | Stops forwarding; the port in the sandbox stays open. In Rust, dropping it does the same. |

## Environment variables

| Variable | Read by | What it does |
| --- | --- | --- |
| `VIRTX_CORE_LIB` | Clients | The `libvirtx_core` to open, when the program has not loaded one itself. |
| `VIRTX_STDIO` | `spawn`, CLI | A server to start as it is, in place of the fetched `virtx-stdio`. |
| `VIRTX_STDIO_VERSION` | `spawn`, CLI | Another version of `virtx-stdio` to fetch. |
| `VIRTX_DIST_URL` | `spawn`, CLI | Where releases are fetched from. |
| `VIRTX_HOME` | `spawn`, CLI | Where virtx keeps what it fetches on this machine. |
| `VIRTX_HOST` | CLI | A server's base URL, reached over HTTP when neither `--host` nor `--server` is given. |
| `VIRTX_TOKEN` | CLI | The bearer token sent to the server reached over HTTP, at `--host` or `VIRTX_HOST`. |
| `VIRTX_PROJECT` | CLI | The project the requests belong to, when `--project` is not given. |
| `VIRTX_OIDC_ISSUER`, `VIRTX_OIDC_CLIENT_ID` | CLI | The provider `virtx login` signs in to and the client it signs in as, when `--issuer` and `--client-id` are not given. See [Signing in](https://virtx.sh/docs/reference/cli/#signing-in). |
| `VIRTX_OIDC_CLIENT_SECRET` | CLI | That client's secret, for a provider that gives its public clients one, when `--client-secret` is not given. |
| `VIRTX_PARK_AFTER_MS` | Server | How long a sandbox is unused before its VM is stopped, in milliseconds; `0` for never. Five minutes by default. |
| `VIRTX_GUEST_SILENCE` | Server | How long a sandbox's guest may answer nothing before its VM is ended, as one that powered off, in seconds, and no less than ten; `0` for never: a guest that halts, as `halt -f` leaves it, or stops answering. A minute by default. |
