ReferenceSDK

Rust SDK

Install the Rust SDK, run a command on a computer and look up the client, computers, exec, files and errors

The Rust SDK runs computers from Rust code. It is async on tokio, and every call returns a nevia::Result, with nevia::Error as the one error type. The SDK is in early access, so names and behaviour can change.

The quick start creates a computer, runs a command on it, writes and reads a file and deletes the computer. The reference after it covers the client, computers, exec, files and errors.

Prerequisites

You need:

  • Rust 1.97.1 or later, with the 2024 edition.
  • A Nevia workspace where you have the admin or editor role.
  • The nevia CLI, signed in with nevia login. The Quickstart shows how to install it.

Install the SDK

Invited testers only

The SDKs are in early access for invited testers. To ask for access, see Request access to Nevia.

From your project's root, download the SDK bundle. It unpacks to vendor/nevia-sdk-0.1.0/:

curl -fsSL --oauth2-bearer "$(nevia auth access-token)" https://sdk.nevia.cloud/0.1.0.tar.gz | tar -xz

Then add the SDK from it:

cargo add --path vendor/nevia-sdk-0.1.0/rust/sdk-rust
cargo add tokio --features macros,rt-multi-thread

If your Cargo.toml has a [workspace] table, add exclude = ["vendor"] to it.

Authenticate

The SDK uses your nevia login session, so a signed-in machine needs nothing more. A server or CI job uses a service-account key instead:

export NEVIA_KEY_FILE="$HOME/path/to/key.json"

Use an automation key file shows how to create one. If you belong to more than one workspace, set NEVIA_WORKSPACE to the workspace ID too.

Create a computer and run a command

Save this as src/main.rs:

use nevia::{Client, Nevia};

#[tokio::main]
async fn main() -> nevia::Result<()> {
    let nevia = Nevia::new(Client::from_env()?);
    let computer = nevia
        .computers()
        .create()
        .image("docker.io/library/debian:12-slim")
        .await?;
    println!("Computer: {}", computer.id());

    let result = computer.exec("uname -sr").await?;
    println!("Exit code: {}, output: {}", result.exit_code, result.stdout.trim());

    computer.files().write("/tmp/hello.txt", "Hello from Nevia!\n").await?;
    if let Some(text) = computer.files().read_text("/tmp/hello.txt").await? {
        print!("{text}");
    }

    computer.delete().await?;
    Ok(())
}

Run it:

cargo run

The computer ID and kernel version in the output vary:

Computer: 01d69b2m9d26k14b244xjwmp9mb
Exit code: 0, output: Linux 6.1.191
Hello from Nevia!

Awaiting create() returns once the computer is ready, so the first command runs at once. A command that exits nonzero still returns a result. Check result.exit_code or result.success() to see whether it succeeded.

Clean up

The SDK never deletes a computer for you. computer.delete() deletes it and waits until it is gone, and succeeds if it is already gone. The ? operator returns early on an error, so a failure between create() and delete() leaves the computer running. Call delete() on the error path too, or run nevia ls afterwards to find and remove leftovers.

To keep a computer after the program ends, skip delete() and save its ID:

let computer = nevia
    .computers()
    .create()
    .image("docker.io/library/debian:12-slim")
    .await?;
println!("{}", computer.id());

A later program reconnects with nevia.computer(saved_id) and calls computer.delete() when it is done.

Reference

Client

Client::builder()
    .base_url(url)
    .workspace(id)
    .token(token)
    .key_file(path)
    .credentials(credentials)
    .build()?

Client::from_env() is Client::builder().build(). Nevia::new(client) wraps a client in the resources used on this page, and Nevia::from_env() does both steps.

Builder methodDescription
token(token)Bearer token string
key_file(path)Path to a service-account key file
credentials(credentials)Any Credentials value (defaults to Credentials::from_env())
workspace(id)Workspace ID (defaults to your only workspace)
base_url(url)API base URL (defaults to production)
http_client(client)Your own reqwest::Client, for proxies or custom TLS
validate(on)Check requests against the API contract before sending (default true)
build()Build the Client, returning a Result

The client looks for credentials in this order:

  1. The token, key_file or credentials builder method.
  2. NEVIA_TOKEN.
  3. NEVIA_KEY_FILE, or NEVIA_KEY with the key's JSON.
  4. Your nevia login session.

The workspace is the workspace builder method, then NEVIA_WORKSPACE, then the only workspace you belong to. NEVIA_API_URL sets the base URL when base_url is not called.

Client and Nevia are cheap to clone, and clones share connections and credentials. Neither needs closing, and dropping them leaves your computers running.

MemberDescription
nevia.computers()Create, get, find and list computers
nevia.computer(id)Handle to an existing computer, without a request
nevia.workspace().awaitID of the selected workspace
nevia.in_workspace(id)Nevia scoped to another workspace, on the same connections

Computers

MethodDescription
computers().create()Builder for a new computer, created when awaited
computers().get(id).awaitGet a computer by ID
computers().find(name).awaitFirst computer whose name is exactly name, as an Option
computers().list()Stream over every computer in the workspace

The create() builder takes these methods before you await it:

Builder methodDescription
image(image)OCI image the computer runs
name(name)Name, unique in the workspace
env(name, value)Stored environment variable (call it once per variable)
from_checkpoint(id)Start from a checkpoint instead of an image
wait(bool)Wait until the computer is ready (default true)
key(key)Idempotency key, so repeated creates return one computer

list() narrows with .field("state", "sleeping") and yields Result<Computer> items, so import futures::TryStreamExt to collect it.

Awaiting create() returns a Computer. If the wait for the computer to become ready fails, the computer still exists. The error's resource() holds its record, and computers().left_by(&error) returns a Computer to delete.

On a computer:

MemberDescription
id()Computer ID
info()Option<&ComputerInfo>, the record as last read
refresh().awaitFetch the latest ComputerInfo
sleep().awaitSleep the computer and wait until it is sleeping
wake().awaitWake the computer and wait until it is ready
ready().awaitWake it if asleep and wait until it can run commands
branch(name)Builder for a branch of the computer (name is an Option<&str>)
delete().awaitDelete the computer (succeeds if it is already gone)

ComputerInfo has id, name, state, image, url, protected and more. state is a ComputerState that maps to a lifecycle state.

A branch is a new computer. Awaiting branch(name) creates it, and it takes wait(bool) and key(key) like create(). The SDK does not delete it for you, so call delete() on the branch when you are done.

Exec

computer.exec(command)
    .cwd(dir)
    .env(name, value)
    .envs(vars)
    .stdin(text)
    .timeout(duration)
    .direct()
    .await?

exec() runs a command to completion and returns an ExecOutput when awaited.

Argument or methodDescription
commandShell string (runs under sh -c), or a list of arguments
cwd(dir)Absolute working directory on the computer
env(name, value)Extra environment variable for this command
envs(vars)Extra environment variables from an iterator of pairs
stdin(text)Text sent to the command's standard input (up to 1 MiB)
timeout(duration)Duration before the command is stopped (whole seconds, rounded up)
direct()Run with direct exec instead of through the API
max_output_bytes(bytes)Bytes kept from the end of each stream with direct exec

When the timeout passes, the SDK stops the command's process group and returns the output so far with timed_out set to true.

Exec runs through the API by default, which ends a request after about 50 seconds. Direct exec sends the command straight to the computer instead, so it suits longer commands. It keeps the last 64 KiB of each output stream and sets truncated when it drops output. See Limits and workarounds.

ExecOutput fieldDescription
exit_codeExit code of the command
signalSignal that ended the command (0 when none)
stdout, stderrOutput of the command, as String
timed_outWhether timeout stopped the command
truncatedWhether direct exec dropped output

ExecOutput::success() returns true when exit_code and signal are 0 and the command did not time out.

Files

computer.files() reads and writes files on the computer. Every path is a path on the computer.

MethodDescription
read(path).awaitFile content as Option<Vec<u8>>, None when there is no file
read_text(path).awaitFile content as Option<String>, None when there is no file
write(path, data).awaitWrite a whole file from any AsRef<[u8]>, creating parent directories
remove(path)Builder that removes a file when awaited

remove(path) takes recursive() for a directory tree and force() to ignore a path that is not there.

write() replaces the file in one step, so a reader never sees it half written. read_text() fails with the code not_text when the file is not UTF-8. A failed read, write or remove fails with the code command_failed.

Errors

Every SDK and API error is a nevia::Error. A command that exits nonzero is a result, not an error.

use nevia::{Client, Nevia};

#[tokio::main]
async fn main() -> nevia::Result<()> {
    let nevia = Nevia::new(Client::from_env()?);
    match nevia.computers().get("01d4cnjk3xg90y576w8y6t4gdwm").await {
        Ok(computer) => println!("Found {}", computer.id()),
        Err(error) if error.is("not_found") => println!("No such computer"),
        Err(error) => return Err(error),
    }
    Ok(())
}
MethodDescription
status()HTTP status (0 when the call failed before an answer)
code()Error code, such as not_found or invalid_state
message()Message for a person to read
details()Extra facts about the error, as a JSON map
op()Name of the operation that failed
request_id()Option<&str> API request ID to quote when you report a problem
retry_after()Option<f64> seconds to wait before retrying
resource()Option<&Value> record of what the call created before it failed
is(code)Whether the code is code
is_transport()Whether the request may not have reached the API

New codes can appear, so treat a code you don't recognise as a generic failure.

On this page