> Markdown version of https://tuna.am/en/docs/guides/install/sdk/rust/. Documentation index: [llms.txt](https://tuna.am/en/llms.txt), full text in one file: [llms-full.txt](https://tuna.am/en/llms-full.txt). Any page is available as Markdown: append `.md` to its URL without the trailing slash.

# Rust

The Rust SDK opens Tuna tunnels straight from your code: expose a local HTTP or TCP service at a public address without installing `tuna`.

* Two ways in: `listen` returns a `Tunnel` that accepts connections as byte streams (`AsyncRead + AsyncWrite`), `forward` proxies them to a local address.
* Survives network failures: reconnects and keeps the same public address.
* Runs on Tokio. SSH is [russh](https://crates.io/crates/russh), TLS is rustls, cryptography is `ring`.

> **Info.** The API is not stable yet: it may change before v1.

The package is [tuna-sdk](https://crates.io/crates/tuna-sdk) on crates.io, source code is on [GitHub](https://github.com/yuccastream/tuna-sdk-rust).

## Installation

```shell
cargo add tuna-sdk

```

The library name is `tuna_sdk`. Requires Rust 1.89 or later and a C compiler for `ring` (`gcc` or `clang`; neither cmake nor Go is needed).

## Authentication

Create an [API key](https://my.tuna.am/api_keys?lang=en) with **Run tunnels** enabled (the **For tunnels** preset) and pass it in `Options::api_key` or the `TUNA_API_KEY` environment variable.

## Accept connections

```rust
use tuna_sdk::{Options, Protocol};

let tunnel = tuna_sdk::listen(Options {
    protocol: Protocol::Http,
    ..Default::default()
})
.await?;
println!("public URL: {}", tunnel.url());

while let Ok(mut visitor) = tunnel.accept().await {
    tokio::spawn(async move {
        let mut local = tokio::net::TcpStream::connect("127.0.0.1:8080").await?;
        tokio::io::copy_bidirectional(&mut visitor, &mut local).await?;
        Ok::<_, std::io::Error>(())
    });
}

```

`close` stops accepting and reconnecting, but the tunnel stays connected until the last accepted stream is released; `wait` returns after that. `abort` cuts off all accepted streams at once. Dropping the `Tunnel` closes it the same way as `close`.

## Forward to a local service

`forward` proxies connections from the tunnel to a local address, `host:port` or `unix:///path/to.sock`:

```rust
use std::sync::Arc;
use tuna_sdk::{Event, Options, Protocol};

tuna_sdk::forward(
    Options {
        protocol: Protocol::Tcp,
        port: "my-db".into(),
        on_event: Some(Arc::new(|e: &Event| {
            if let Event::Connected { url } = e {
                eprintln!("forwarding {url} -> 127.0.0.1:5432");
            }
        })),
        ..Default::default()
    },
    "127.0.0.1:5432",
)
.await?;

```

`forward` runs until the tunnel ends for good. To stop it, drop the future, for example with `tokio::select!` on a shutdown signal.

## Options

| `Options` field             | Meaning                                                                                                                                                          |
| --------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `protocol`                  | `Protocol::Http` (default) or `Protocol::Tcp`                                                                                                                    |
| `api_key`                   | API key, defaults to `$TUNA_API_KEY`                                                                                                                             |
| `subdomain`, `domain`       | HTTP: [reserved subdomain](https://tuna.am/en/docs/tunnels/http.md#reserved-subdomain) or [custom domain](https://tuna.am/en/docs/tunnels/http.md#custom-domain) |
| `port`                      | TCP: [reserved port](https://tuna.am/en/docs/tunnels/ports.md) or its alias                                                                                      |
| `proxy_protocol`            | TCP: [PROXY protocol](https://tuna.am/en/docs/tunnels/tcp.md#proxy-protocol) version, `1` or `2`                                                                 |
| `cidr_allow`, `cidr_deny`   | TCP: client subnets allowed or rejected by the Tuna node                                                                                                         |
| `on_event`                  | callback for tunnel events                                                                                                                                       |
| `connect_timeout`           | limit on the wait for the first connection; `None` means no limit                                                                                                |
| `server_url`, `client_name` | API address and client name reported to the server                                                                                                               |

## Events and errors

`on_event` receives `Event::Connected`, `Reconnecting`, `Reconnected`, `Banner`, `SessionExpiring`, `Terminated` and `LocalError`; `Event::name` returns the snake_case name. Calls never overlap and run on the tunnel's tasks, so keep the callback short.

Network failures and temporary server errors are retried: the pause grows from 1 to 15 seconds with random jitter, and `Retry-After` is respected. If the node does not respond for 15 seconds, `Reconnecting` arrives with `Error::KeepAliveTimeout` and the tunnel reconnects. The tunnel ends with an error when retrying is pointless; check it with `Error::is_permanent`:

* `Error::Server`: the API rejected the request — bad or revoked key, missing permission, unknown reserved name, unpaid plan;
* `Error::Terminated`: the server closed the tunnel — it was deleted, suspended or hit the session time limit.

## Behavior worth knowing

* When the visitor closes its side of a forwarded connection, the connection is closed in both directions: a response sent after that is lost.
* The `Host` header and the PROXY protocol header reach your service as sent.
* The API client uses the system root certificates and does not go through an HTTP proxy. Connections to Tuna nodes are plain SSH.
