tuna

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 26, 2026 License: MIT Imports: 21 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

tuna-sdk-go

Go Reference

Open tuna.am tunnels straight from Go code: expose a local HTTP or TCP service at a public address without installing the tuna CLI.

  • Two ways in: Listen returns a net.Listener for your own server, Forward proxies connections to a local address.
  • Survives network failures: reconnects with backoff and keeps the same public address.
  • Small: only the standard library and golang.org/x/crypto/ssh.

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

Install

go get github.com/yuccastream/tuna-sdk-go

The package name is tuna. Requires Go 1.26 or later.

Authentication

Create an API key with the tunnels:connect scope at my.tuna.am and pass it in Options.APIKey or the TUNA_API_KEY environment variable.

Serve HTTP without a local port

ln, err := tuna.Listen(ctx, tuna.Options{Protocol: "http"})
if err != nil {
	return err
}
defer ln.Close()

fmt.Println("public URL:", ln.URL())
return http.Serve(ln, handler)

Close works like on any net.Listener: http.Server.Shutdown lets in-flight requests finish before the tunnel disconnects.

Forward to a local service

err := tuna.Forward(ctx, tuna.Options{
	Protocol: "tcp",
	Port:     "my-db",
	OnEvent: func(e tuna.Event) {
		if e.Type == tuna.EventConnected {
			log.Printf("forwarding %s -> 127.0.0.1:5432", e.URL)
		}
	},
}, "127.0.0.1:5432")

The local address is host:port or unix:///path/to.sock. Forward blocks until ctx is cancelled or the tunnel ends for good.

Options

Field Meaning
Protocol http or tcp, required
APIKey API key, defaults to $TUNA_API_KEY
Subdomain, Domain reserved subdomain or custom domain for HTTP
Port reserved TCP port or its alias
ProxyProtocol PROXY protocol header version for TCP: 1 or 2
CIDRAllow, CIDRDeny client CIDRs filtered by the tuna.am node, TCP only
Location only for names and ports reserved in the legacy ru or nl zones; empty lets the server pick
OnEvent callback for tunnel events
ConnectTimeout limit on the wait for the first connection; zero means no limit
ServerURL, TLSConfig, ClientName API address, TLS settings for it, client name reported to the server

Events and errors

OnEvent receives connected, reconnecting, reconnected, banner, session_expiring, terminated and local_error. Calls never overlap and run on the tunnel's goroutines, 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. The tunnel ends with an error when retrying is pointless; check it with IsPermanent:

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

Behaviour worth knowing

  • The context passed to Listen bounds the whole life of the tunnel, not only the first connection; cancelling it cuts off every accepted connection. To give up early when the tunnel does not come up, set ConnectTimeout.
  • Close stops accepting and reconnecting, but the tunnel stays connected until the last accepted connection is closed. http.Server.Shutdown does not wait for or close hijacked connections such as WebSockets: they keep the tunnel open until your code closes them or the context is cancelled.
  • When the visitor closes its side of a 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 is net/http and honours HTTPS_PROXY. Connections to tuna.am nodes are plain SSH over TCP and do not use the proxy.
  • Use TLSConfig for a private CA or for environments without system root certificates, such as scratch images.

Protocol

The SDK implements the public tuna.am client protocol: POST /v1/connect followed by a standard SSH remote forward to the node. Docs: tuna.am/docs/guides/client-protocol.

tuna-tiny, a 2 MB tunnel client for routers, embedded devices and scratch containers, is built on this SDK.

Contributing

This repository is a read-only mirror of the SDK directory in the tuna.am monorepo. Issues and pull requests are welcome here: accepted changes are applied upstream and come back with the next release.

License

MIT

Documentation

Overview

Package tuna opens tuna.am tunnels from Go code.

Listen returns a net.Listener that receives connections arriving at the tunnel's public address. Forward proxies them to a local address.

A tunnel survives network failures: it reconnects with backoff and keeps its public address. It ends on Close, cancellation of its context or a permanent error (see IsPermanent).

Index

Examples

Constants

View Source
const (
	// Version is the SDK version.
	Version = "0.1.0"
	// DefaultServerURL is the tuna.am API used when Options.ServerURL is empty.
	DefaultServerURL = "https://api.tuna.am"
)

Variables

View Source
var ErrKeepAliveTimeout = errors.New("tuna: keepalive timeout")

ErrKeepAliveTimeout means the node stopped answering keepalive requests.

Functions

func Forward

func Forward(ctx context.Context, o Options, localAddr string) error

Forward proxies tunnel connections to localAddr ("host:port" or "unix:///path.sock"). It blocks until a permanent error occurs or ctx is cancelled. Cancellation after the tunnel came up returns nil; before that Forward fails like Listen.

Example
package main

import (
	"context"
	"log"
	"os"
	"os/signal"

	tuna "github.com/yuccastream/tuna-sdk-go"
)

func main() {
	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
	defer stop()

	err := tuna.Forward(ctx, tuna.Options{
		Protocol:  "tcp",
		Port:      "my-db",
		CIDRAllow: []string{"203.0.113.0/24"},
		OnEvent: func(e tuna.Event) {
			switch e.Type {
			case tuna.EventConnected, tuna.EventReconnected:
				log.Printf("forwarding %s -> 127.0.0.1:5432", e.URL)
			case tuna.EventReconnecting:
				log.Printf("connection error (%v), retry in %s", e.Err, e.RetryIn)
			case tuna.EventSessionExpiring:
				log.Printf("session expires in %s", e.ExpiresIn)
			case tuna.EventLocalError:
				log.Printf("local service unavailable: %v", e.Err)
			case tuna.EventBanner, tuna.EventTerminated:
				log.Print(e.Message)
			}
		},
	}, "127.0.0.1:5432")
	if err != nil {
		log.Print(err)
	}
}

func IsPermanent

func IsPermanent(err error) bool

IsPermanent reports whether retrying after err is pointless.

Types

type Event

type Event struct {
	// Type is the kind of the event.
	Type EventType
	// URL is the public address, set for EventConnected and EventReconnected.
	URL string
	// Message is human-readable text, set for EventBanner and EventTerminated.
	Message string
	// Reason is the machine-readable cause, set for EventTerminated.
	Reason string
	// Err is the cause, set for EventReconnecting and EventLocalError.
	Err error
	// RetryIn is the delay before the next attempt, set for EventReconnecting.
	RetryIn time.Duration
	// ExpiresIn is the time left, set for EventSessionExpiring.
	ExpiresIn time.Duration
}

Event describes a change in the tunnel state.

type EventType

type EventType string

EventType identifies the kind of an Event.

const (
	// EventConnected is sent once, when the tunnel comes up for the first time.
	EventConnected EventType = "connected"
	// EventReconnected is sent when the tunnel comes up again after a failure.
	EventReconnected EventType = "reconnected"
	// EventReconnecting is sent after a failed attempt or a lost connection,
	// before the next attempt.
	EventReconnecting EventType = "reconnecting"
	// EventBanner carries a server message for the user.
	EventBanner EventType = "banner"
	// EventSessionExpiring warns that the session time limit is near.
	EventSessionExpiring EventType = "session_expiring"
	// EventTerminated is sent when the server closes the tunnel for good.
	EventTerminated EventType = "terminated"
	// EventLocalError reports a failure to reach the local address in Forward.
	EventLocalError EventType = "local_error"
)

type Options

type Options struct {
	// APIKey is a tuna.am API key with the tunnels:connect scope.
	// Defaults to the TUNA_API_KEY environment variable.
	APIKey string
	// Protocol is "http" or "tcp".
	Protocol string
	// Location is needed only for names and ports reserved in the legacy
	// "ru" or "nl" zones. Empty lets the server pick the zone.
	Location string
	// Subdomain is a reserved subdomain for HTTP tunnels.
	Subdomain string
	// Domain is a custom domain for HTTP tunnels.
	Domain string
	// Port is a reserved TCP port or its alias.
	Port string
	// ProxyProtocol enables the PROXY protocol header (1 or 2) for TCP tunnels.
	ProxyProtocol int
	// CIDRAllow lists client CIDRs allowed to reach a TCP tunnel.
	CIDRAllow []string
	// CIDRDeny lists client CIDRs rejected by a TCP tunnel.
	CIDRDeny []string
	// ServerURL is the tuna.am API address. Defaults to DefaultServerURL.
	ServerURL string
	// TLSConfig is used for connections to the API. Nil means the system roots.
	TLSConfig *tls.Config
	// ClientName is reported to the server. Defaults to "tuna-sdk-go/<Version>".
	ClientName string
	// ConnectTimeout limits how long Listen and Forward wait for the tunnel
	// to come up for the first time. Zero means no limit. Reconnects are not
	// limited.
	ConnectTimeout time.Duration
	// OnEvent receives tunnel events. Calls never overlap, but they come from
	// the tunnel's own goroutines, so OnEvent must return quickly. It may
	// call Tunnel.Close.
	OnEvent func(Event)
}

Options configures a tunnel. Only Protocol is required.

type ServerError

type ServerError struct {
	// Status is the HTTP status code.
	Status int `json:"-"`
	// Code is the machine-readable error code.
	Code string `json:"code"`
	// Message is the human-readable error text.
	Message string `json:"error"`
	// RequestID identifies the request for tuna.am support.
	RequestID string `json:"request_id"`
	// RetryAfter is the delay requested by the server, if any.
	RetryAfter time.Duration `json:"-"`
	// contains filtered or unexported fields
}

ServerError is an error response from the tuna.am API.

func (*ServerError) Error

func (e *ServerError) Error() string

type TerminatedError

type TerminatedError struct {
	// Reason is the machine-readable cause, e.g. "deleted" or "session_limit".
	Reason string
}

TerminatedError means the server closed the tunnel for good.

func (*TerminatedError) Error

func (e *TerminatedError) Error() string

type Tunnel

type Tunnel struct {
	// contains filtered or unexported fields
}

Tunnel is a net.Listener for connections to the tunnel's public address. It survives reconnects; Accept fails only after Close or a permanent error.

func Listen

func Listen(ctx context.Context, o Options) (*Tunnel, error)

Listen connects the tunnel and returns once it is up or a permanent error occurs.

ctx bounds the whole life of the tunnel, not only the first connection: cancelling it closes the tunnel together with every accepted connection. Use Options.ConnectTimeout to limit the wait for the first connection. If ctx or ConnectTimeout ends before the tunnel comes up, the returned error wraps context.DeadlineExceeded or context.Canceled and the last failure.

Example
package main

import (
	"context"
	"fmt"
	"log"
	"net/http"

	tuna "github.com/yuccastream/tuna-sdk-go"
)

func main() {
	ln, err := tuna.Listen(context.Background(), tuna.Options{Protocol: "http"})
	if err != nil {
		log.Fatal(err)
	}
	defer func() { _ = ln.Close() }()

	fmt.Println("public URL:", ln.URL())
	err = http.Serve(ln, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		_, _ = fmt.Fprintln(w, "hello from", r.Host)
	}))
	log.Print(err)
}

func (*Tunnel) Accept

func (t *Tunnel) Accept() (net.Conn, error)

Accept waits for the next connection to the public address. Accepted connections support deadlines, so http.Server timeouts and Hijack work.

func (*Tunnel) Addr

func (t *Tunnel) Addr() net.Addr

Addr returns the public address as a net.Addr with network "tuna".

func (*Tunnel) Close

func (t *Tunnel) Close() error

Close stops accepting connections and reconnecting, like Close of any net.Listener, so http.Server.Shutdown lets in-flight requests finish. Connections accepted earlier keep working: the tunnel stays connected to the node until the last of them is closed. Cancel the context passed to Listen to cut them off as well. Close does not wait.

func (*Tunnel) URL

func (t *Tunnel) URL() string

URL returns the current public address, e.g. https://name.tuna.am or tcp://ru.tuna.am:40000.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL