> Markdown version of https://tuna.am/en/docs/guides/install/sdk/ruby/. 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.

# Ruby

The Ruby 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: `Tuna::SDK.listen` hands you each connection as a socket, `Tuna::SDK.forward` proxies connections to a local address.
* Survives network failures: reconnects and keeps the same public address.
* Dependencies are only the standard library and [net-ssh](https://github.com/net-ssh/net-ssh).

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

The package is [tuna-sdk](https://rubygems.org/gems/tuna-sdk) on RubyGems, source code is on [GitHub](https://github.com/yuccastream/tuna-sdk-ruby).

## Installation

```shell
gem install tuna-sdk

```

Or in your `Gemfile`:

```ruby
gem "tuna-sdk"

```

Requires Ruby 3.1 or later. net-ssh 8 needs the `openssl` gem 3.2 or later: Ruby 3.3 and later already ship it, while on 3.1 and 3.2 it is built during installation and the build needs OpenSSL headers (`libssl-dev` or equivalent).

## 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 `api_key` or the `TUNA_API_KEY` environment variable.

## Forward to a local service

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

```ruby
require "tuna/sdk"

Tuna::SDK.forward({ protocol: "http" }, "127.0.0.1:3000") do |tunnel|
  puts "public URL: #{tunnel.url}"
  tunnel.wait
end

```

Without a block, `forward` blocks until the tunnel ends for good. With a block, it yields the connected tunnel and closes it when the block returns. `tunnel.wait` waits for `tunnel.close`, for example from a signal handler:

```ruby
trap("TERM") { Thread.new { tunnel.close } }

```

## Handle connections yourself

```ruby
Tuna::SDK.listen(protocol: "tcp", port: "my-db") do |tunnel|
  puts "public URL: #{tunnel.url}"
  while (conn = tunnel.accept)
    Thread.new(conn) do |c|
      c.write(c.gets)
    ensure
      c.close
    end
  end
end

```

`accept` returns a `UNIXSocket` connected to the visitor, or `nil` once the tunnel is closed. Without a block, `listen` returns the tunnel.

## Options

`options` is a Hash or `Tuna::SDK::Options`:

| Key                         | Meaning                                                                                                                                                          |
| --------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `protocol`                  | `"http"` or `"tcp"`, required                                                                                                                                    |
| `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 that receives a `Tuna::SDK::Event`                                                                                                                      |
| `connect_timeout`           | limit on the wait for the first connection, in seconds; `nil` means no limit                                                                                     |
| `server_url`, `client_name` | API address and client name reported to the server                                                                                                               |

## Events and errors

`on_event` receives a `Tuna::SDK::Event` of type `:connected`, `:reconnecting`, `:reconnected`, `:banner`, `:session_expiring`, `:terminated` or `:local_error`, with the fields `url`, `message`, `reason`, `error`, `retry_in` and `expires_in` (in seconds) when the event has them. Calls never overlap and run on the tunnel's threads, so keep the callback short.

```ruby
on_event = ->(e) { warn "#{e.type} #{e.url || e.error&.message}" }
Tuna::SDK.forward({ protocol: "http", on_event: on_event }, "127.0.0.1:3000")

```

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 stops responding, `:reconnecting` arrives after 15 seconds with a `Tuna::SDK::KeepAliveTimeoutError`. The tunnel ends with an error when retrying is pointless; check it with `Tuna::SDK.permanent?(err)`:

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

## Behavior worth knowing

* `close` stops accepting and reconnecting, but the tunnel stays connected until the last accepted connection is closed.
* When either side of a forwarded connection closes, the connection is closed in both directions.
* The `Host` header and the PROXY protocol header reach your service as sent.
* The SSH connection runs on a separate tunnel thread; `accept`, `wait` and `close` can be called from any thread.
* The API client is `Net::HTTP`. For a private CA, set `SSL_CERT_FILE`.
