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 ¶
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 ¶
var ErrKeepAliveTimeout = errors.New("tuna: keepalive timeout")
ErrKeepAliveTimeout means the node stopped answering keepalive requests.
Functions ¶
func Forward ¶
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)
}
}
Output:
func IsPermanent ¶
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 ¶
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)
}
Output:
func (*Tunnel) Accept ¶
Accept waits for the next connection to the public address. Accepted connections support deadlines, so http.Server timeouts and Hijack work.
func (*Tunnel) Close ¶
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 ¶
URL returns the current public address, e.g. https://name.tuna.am or tcp://ru.tuna.am:40000.