# Rust

> Install the dvm-run crate on tokio, use Client and builders, and clean up sandboxes with scope.

This is the Markdown of https://docs.dvm.run/sdks/rust/. Every page of the dvm.run docs is served as Markdown at its address plus `.md`; the list of pages is https://docs.dvm.run/llms.txt.

Add the Rust SDK to a tokio project and learn its conventions for builders, cleanup, and errors.



```sh
cargo add dvm-run tokio --features tokio/macros,tokio/rt-multi-thread
```

The `dvm-run` crate on crates.io targets Rust 1.88 or newer (edition 2024) with tokio futures. API types live in `dvm-api`, re-exported as `dvm_run::api`. Run `cargo install dvm-run` for the `dvm-run` CLI ([Getting in](/start/access/)).

## Client and builders

Create one `Client`: `Client::from_env()` reads `DVM_API_URL` and `DVM_API_KEY` (or the key saved by `dvm-run login`); `Client::new(url, key)` takes them directly. Sandbox creation, commands, writes, seeks, and steps each return a builder: set what differs, then `.await` it.

`rust/dvm-run/examples/programs.rs`

```rust
let sandbox = client
    .create_sandbox("alpine:3.20")
    .command(["sh", "-c", "echo out; echo err >&2; exit 3"])
    .name("exits-three")
    .cpus(2)
    .memory_mib(2048)
    .seed(7)
    .await?;
println!("{}", sandbox.wait().await?);
let output = sandbox.output().await?;
println!("{:?}", String::from_utf8_lossy(output.stdout.bytes()));
println!("{:?}", String::from_utf8_lossy(output.stderr.bytes()));
println!("{}", sandbox.state().await?.kind());
```

`create_sandbox` resolves once the sandbox runs (or has exited). `connect_sandbox(id)` attaches to an existing sandbox. `Sandbox` is `Clone`, and clones share one session.

## End a sandbox

Dropping a `Sandbox` leaves it running. Wrap work in `scope`, which cleans up when the closure returns, fails, or is dropped:

* a session (a sandbox accepting commands) closes its input, and `scope` waits for exit;
* a paused sandbox or one-program sandbox is stopped;
* an ended sandbox is left unchanged.

Or call `end()` or `stop()` directly. Dropping a `create_sandbox` future before startup stops the sandbox.

## Bytes and results

`run` and `Command::wait` return a `CommandResult` with `exit_code`, plus `stdout` and `stderr` as `Vec<u8>`. A command’s exit code is never an error. Commands take `impl Into<CommandLine>`: `&str` or `String` runs as a shell script; an array or `Vec` of strings runs as argv.

## Errors

Every call returns `dvm_run::Result<T>` with `dvm_run::Error`:

* **HTTP statuses:** `InvalidRequest` (400), `Authentication` (401), `NotFound` (404), `Conflict` (409), and `Refused { status, reason }` for others (such as 402 and 403).
* **Lifecycle:** `SandboxEnded` and `SandboxFailed` when the sandbox ended first.
* **Session server:** `SandboxRequest` when the sandbox rejects a request.
* **Client/transport:** `NoApiKey`, `Credentials`, `Network`, `Unexpected`.

See [Errors](/reference/errors/).

`rust/dvm-run/examples/errors.rs`

```rust
let made = client
    .create_sandbox("alpine:3.20")
    .command(["true"])
    .cpus(64)
    .await;
match made {
    Ok(sandbox) => match sandbox.wait().await {
        Err(Error::SandboxFailed { reason, .. }) => println!("dvm ended it: {reason}"),
        waited => println!("{:?}", waited?),
    },
    Err(Error::InvalidRequest { reason }) => println!("400 {reason}"),
    Err(Error::Refused {
        status: 402,
        reason,
    }) => println!("out of credit: {reason}"),
    Err(Error::Refused {
        status: 403,
        reason,
    }) => println!("not let in yet: {reason}"),
    Err(error) => return Err(error),
}
```

Calling a command, file call, or `end` on a one-program sandbox returns `Error::Conflict` locally (Python and TypeScript raise a plain `DvmError`). A signal outside 1 to 64 returns `Error::SandboxRequest`.

## Where next

* [Sessions](/guides/sessions/): run commands and transfer files.
* [Rust reference](/reference/rust/), plus docs on [docs.rs/dvm-run](https://docs.rs/dvm-run) and [docs.rs/dvm-api](https://docs.rs/dvm-api).
* [crates.io](https://crates.io/crates/dvm-run) and [source](https://github.com/deterministic-machines/sdk/tree/main/rust).
