tunnel

package
v0.8.2 Latest Latest
Warning

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

Go to latest
Published: Nov 14, 2026 License: MIT Imports: 15 Imported by: 0

Documentation

Overview

Package tunnel carries HTTP exchanges over a message channel, so an http.Handler can serve clients that have no socket to it: a webview behind a desktop shell, a process on the other end of stdio, a page across a WebSocket or a MessagePort.

Serve answers the calls arriving on a Conn with an http.Handler. Client is the other end: an http.RoundTripper that sends requests through a Conn. The TypeScript client's syncplane/tunnel module speaks the same protocol, which is defined by syncplane.tunnel.v1.Frame.

The handler can be anything. To serve the sync engine in process, pass a mux of server.Server.Handlers. To forward to a remote server, pass an httputil.ReverseProxy.

A Conn is the only part a host supplies. Anything that sends and receives whole messages in order fits: NewStreamConn adapts a byte stream, and a WebSocket or a host's own stream API needs a wrapper of a few lines.

Example

Example serves a handler over a byte stream and calls it through a Client. In a real app the two ends are two processes, joined by stdio or a socket; here net.Pipe stands in for that.

package main

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

	"github.com/levelfourab/syncplane/engine/tunnel"
)

func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "hello, %s", r.URL.Query().Get("name"))
	})

	serverEnd, clientEnd := net.Pipe()
	go func() {
		_ = tunnel.Serve(context.Background(), tunnel.NewStreamConn(serverEnd), mux)
	}()

	c := tunnel.NewClient(tunnel.NewStreamConn(clientEnd))
	defer c.Close()
	// The host in the URL is ignored; only the path and query reach mux.
	resp, err := (&http.Client{Transport: c}).Get("http://tunnel/hello?name=world")
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(string(body))
}
Output:
hello, world

Index

Examples

Constants

View Source
const DefaultRequestBuffer = 32 << 20

DefaultRequestBuffer is the request buffer Serve uses without WithRequestBuffer: 32 MiB, twice the sync engine's default request limit.

View Source
const MaxFrameSize = 4 << 20

MaxFrameSize is the largest frame, in bytes, that a Conn from NewStreamConn sends or receives. The tunnel itself never produces a frame near it.

Variables

View Source
var ErrCallFailed = errors.New("tunnel: call failed")

ErrCallFailed is returned for a call that the other end ended with an error, such as a handler that aborted mid-response. The returned error wraps it and carries the reason the other end gave.

View Source
var ErrClosed = errors.New("tunnel: channel closed")

ErrClosed is returned for a call through a Client whose channel closed before the call finished, and for any call started after that.

View Source
var ErrFrameTooLarge = errors.New("tunnel: frame exceeds MaxFrameSize")

ErrFrameTooLarge is returned by a Conn from NewStreamConn for a frame above MaxFrameSize.

View Source
var ErrProtocol = errors.New("tunnel: protocol violation")

ErrProtocol is returned by Serve, and by calls through a Client, when the other end sends something that is not a valid tunnel frame or breaks the order the protocol requires. The channel is closed when it happens.

Functions

func Serve

func Serve(ctx context.Context, conn Conn, h http.Handler, opts ...Option) error

Serve answers the calls that arrive on conn with h, until conn closes or ctx ends.

Each call runs h on its own goroutine. The request's context ends when the client cancels the call, the channel closes or ctx ends. The request has no RemoteAddr or TLS state; Host comes from a Host header when the client sent one, and ContentLength from Content-Length, or -1 without it. The ResponseWriter implements http.Flusher, and a flush sends the bytes written so far.

A handler that panics fails only its own call, and the client sees a network failure. The panic is logged unless it is http.ErrAbortHandler.

Serve blocks. Before it returns, it cancels every call in flight, waits for their handlers to return and closes conn. Those calls send nothing more, so the client sees them fail, not finish. It returns nil when the channel reaches io.EOF or ctx ends. Otherwise it returns the error that ended it: a Receive or Send failure, or an error that wraps ErrProtocol.

Example (Forward)

ExampleServe_forward answers a tunnel by forwarding to a remote sync server. The allowlist keeps everything but the client-facing services out of reach, and the proxy, not the tunnel's client, holds the credential.

package main

import (
	"context"
	"io"
	"log"
	"net/http"
	"net/http/httputil"
	"net/url"
	"os"

	"github.com/levelfourab/syncplane/engine/tunnel"
)

func main() {
	remote, err := url.Parse("https://sync.example.com")
	if err != nil {
		log.Fatal(err)
	}
	token := os.Getenv("SYNC_TOKEN")
	proxy := &httputil.ReverseProxy{
		Rewrite: func(r *httputil.ProxyRequest) {
			r.SetURL(remote)
			// Set, not Add: an Authorization header from the tunnel's client
			// never reaches the remote.
			r.Out.Header.Set("Authorization", "Bearer "+token)
		},
		// Send each stream message on as it arrives.
		FlushInterval: -1,
	}
	allow := http.NewServeMux()
	allow.Handle("/syncplane.v1.SyncService/", proxy)
	allow.Handle("/syncplane.v1.PresenceService/", proxy)

	// One end of a stream from the host; stdio stands in for it here.
	conn := tunnel.NewStreamConn(struct {
		io.Reader
		io.Writer
		io.Closer
	}{os.Stdin, os.Stdout, os.Stdin})
	if err := tunnel.Serve(context.Background(), conn, allow); err != nil {
		log.Fatal(err)
	}
}

Types

type Client

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

Client sends HTTP requests through a tunnel to a peer running Serve. It implements http.RoundTripper and multiplexes every request over one Conn.

A Client is safe for concurrent use. Once its channel closes, by Close, by the peer or by a failure, every call in flight fails and so does every later RoundTrip, with an error that wraps ErrClosed or ErrProtocol. Build a new Client over a new Conn to reconnect.

func NewClient

func NewClient(conn Conn) *Client

NewClient returns a Client that owns conn and reads from it until it closes. Close the Client to release conn.

func (*Client) Close

func (c *Client) Close() error

Close closes the channel and fails every call in flight with an error that wraps ErrClosed. It returns the error from closing the Conn, the same on every call.

func (*Client) RoundTrip

func (c *Client) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip implements http.RoundTripper.

The request URL's scheme and host are ignored: the call goes to the path and query on the peer's handler. A non-empty req.Host goes as a Host header. The response body streams as frames arrive and must be closed; closing it before the end cancels the call on the peer, and so does ending the request context. Response bytes are held in memory, without bound, until the caller reads them.

A call the peer fails returns an error that wraps ErrCallFailed: from RoundTrip before the response head arrives, from a body Read after.

type Conn

type Conn interface {
	Send(frame []byte) error
	Receive() ([]byte, error)
	Close() error
}

Conn is one message channel between a tunnel client and a server.

Send transmits one frame as one message. Receive blocks until the next message arrives and returns it whole; it returns io.EOF, or another error, once the channel has closed. Messages must arrive complete, in the order they were sent, and without loss.

The tunnel never calls Send concurrently with another Send, nor Receive concurrently with another Receive, but it calls Send, Receive and Close concurrently with each other. Close must unblock a pending Receive and a pending Send, and may be called more than once. The tunnel does not modify a frame after it passes it to Send, and does not keep a slice that Receive returned.

func NewStreamConn

func NewStreamConn(rwc io.ReadWriteCloser) Conn

NewStreamConn returns a Conn that carries frames over a byte stream, such as stdio, a pipe or a socket. Each frame is written as its length, a 4-byte big-endian unsigned integer, followed by the frame itself. The TypeScript fromByteStream adapter uses the same framing.

Receive returns io.EOF when the stream ends between two frames, and io.ErrUnexpectedEOF when it ends inside one. A frame above MaxFrameSize makes Send and Receive return ErrFrameTooLarge; after Receive does, the stream is out of step and must be closed.

The Conn owns rwc: Close closes it. Send is safe for concurrent use.

type Option

type Option func(*serveOptions)

Option configures Serve.

func WithLogger

func WithLogger(l *slog.Logger) Option

WithLogger sets where Serve reports handler panics. The default is slog.Default(). A nil logger keeps the default.

func WithRequestBuffer

func WithRequestBuffer(n int) Option

WithRequestBuffer bounds the request-body bytes, per call, that Serve holds for a handler that has not read them yet. A call that goes above n fails: its handler's context ends and the client gets an error. Zero or a negative n means DefaultRequestBuffer.

Jump to

Keyboard shortcuts

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