Documentation
¶
Overview ¶
Package tunnel is the preview tunnel's transport: one WebSocket from a host to the gateway, carrying HTTP/2 with the roles reversed — the host runs the HTTP/2 SERVER (Serve), the gateway holds the CLIENT (NewClient) and opens one CONNECT stream per upstream TCP connection (Client.Dial). The protocol on top (paths, headers, refusal reasons, the offer stream) is internal/preview/wire. See docs/design/previews.md ("The host tunnel").
STREAMS: a host's maxConns counts its UPSTREAM connections (CONNECT streams) only. The control streams — the long-lived GET wire.OfferPath and the POST wire.OpenedPath / wire.ClosedPath answers — ride on ControlStreams more HTTP/2 streams above it, so they never queue behind data. The cap on data is kept at both ends: the gateway's Dial takes one of maxConns slots, waiting at most ClientOptions.DialWait for one to free and then failing with max_conns (429); the host refuses a CONNECT past its maxConns with max_conns too, as a backstop.
🔴 PINNED INVARIANT: the gateway's connection receive window is LARGER than (wire.MaxConns + ControlStreams) × its stream receive window (ConnWindow, StreamWindow) — every stream the host's SETTINGS_MAX_CONCURRENT_STREAMS admits. x/net's HTTP/2 client returns connection-level flow credit only as a stream's body is read, so a reader that pauses keeps its whole stream window out of the connection window until it resumes; once paused streams × stream window reach the connection window, EVERY other stream on the tunnel stalls, the control streams included. The same holds in the other direction for the host's upload windows (UploadConnWindow, UploadStreamWindow), where an upstream that stops reading a request body is the paused reader. TestFlowControlInvariantIsPinned and TestPausedReadersCannotStallTheTunnel pin the numbers and the behaviour together.
Index ¶
- Constants
- Variables
- func DialHost(ctx context.Context, endpoint string, hdr http.Header) (*websocket.Conn, *http.Response, error)
- func Serve(ctx context.Context, c *websocket.Conn, h http.Handler, o HostOptions) error
- func Splice(w http.ResponseWriter, r *http.Request, up net.Conn)
- type Client
- type ClientOptions
- type HostOptions
- type RefusedError
Constants ¶
const ( // StreamWindow is the gateway's per-stream receive window (host → gateway, // the response bytes a browser downloads). It is x/net's own client default. StreamWindow = 4 << 20 // ConnWindow is the gateway's connection receive window: (64+4+1) × 4 MiB // = 276 MiB. It is also the most gateway memory one host's paused readers // can hold. ConnWindow = (wire.MaxConns + ControlStreams + 1) * StreamWindow // UploadStreamWindow is the host's per-stream receive window (gateway → // host, request bodies and WebSocket frames a browser sends). UploadStreamWindow = 1 << 20 // UploadConnWindow is the host's connection receive window: // (64+4+1) × 1 MiB = 69 MiB, the most host memory one tunnel's stalled // uploads can hold. UploadConnWindow = (wire.MaxConns + ControlStreams + 1) * UploadStreamWindow )
Flow-control windows, in bytes. See the package comment for why the connection windows are sized from every stream the host admits (wire.MaxConns + ControlStreams), plus one stream of margin.
const ControlStreams = 4
ControlStreams is the HTTP/2 stream headroom above maxConns for the control streams: one long-lived GET wire.OfferPath, plus up to three POST answers (wire.OpenedPath / wire.ClosedPath) in flight at once. An answer is one small request that completes in a round trip, so a fourth concurrent one waits a round trip behind the others — never behind a data stream, which cannot take these slots (the gateway's Dial is capped at maxConns).
const DefaultDialWait = 10 * time.Second
DefaultDialWait is how long Dial waits for one of the host's maxConns upstream slots before refusing with max_conns.
Variables ¶
var ErrClosed = errors.New("tunnel: closed")
ErrClosed ends a tunnel that the peer or the transport closed.
var ErrPeerUnresponsive = errors.New("tunnel: peer did not answer a ping")
ErrPeerUnresponsive ends a tunnel whose peer did not answer a WebSocket ping within one ping interval.
Functions ¶
func DialHost ¶
func DialHost(ctx context.Context, endpoint string, hdr http.Header) (*websocket.Conn, *http.Response, error)
DialHost opens the host's tunnel WebSocket to a gateway endpoint (ws:// or wss://<gateway>/v1/host), sending hdr (the token, wire.VersionHeader, wire.HostNameHeader). The upgrade is forced onto HTTP/1.1: a non-nil, empty TLSNextProto is net/http's documented way to turn HTTP/2 negotiation off, and a WebSocket upgrade cannot ride HTTP/2. A refused dial returns the gateway's response (with wire.VersionRangeHeader on a version refusal). The client never follows a redirect (noredirect): one would re-send the host token to the Location.
🔴 A ws:// DIAL NEVER USES A PROXY (hostProxy): on the overlay-mesh endpoint the dial is plain ws:// — the mesh encrypts the hop — so a proxy would receive the mpt_ bearer token in clear text. A wss:// dial honours the proxy environment as usual: TLS, end to end through the proxy's CONNECT, keeps the token from it, and a host that can only reach the internet through a proxy keeps its previews.
func Serve ¶
Serve runs the host end of a tunnel on c (from DialHost) until ctx ends or the tunnel does, handing every stream the gateway opens to h: GET wire.OfferPath, POST wire.OpenedPath / wire.ClosedPath, and CONNECT (answer with Splice, or wire.WriteRefusal). A CONNECT past maxConns never reaches h: Serve answers it max_conns. It returns ctx's error, ErrPeerUnresponsive, or ErrClosed, and closes c.
func Splice ¶
Splice answers a CONNECT the host has decided to serve: it writes 200, then copies bytes both ways between the stream and up (a loopback connection the host dialed) until the upstream closes, the stream is reset, or the tunnel ends. Every chunk read from up is flushed at once, so a server-sent event is not held back. End of the gateway's side half-closes up (CloseWrite), so a request-then-response upstream still answers. It closes up.
Types ¶
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is the gateway's handle on one host's tunnel. It is an http.RoundTripper for the control streams (wire.OfferPath and friends; any URL host, the path is what routes) and dials CONNECT streams with Dial.
func NewClient ¶
NewClient starts the gateway end of a tunnel on c, a WebSocket the gateway accepted on wire.HostPath (after checking the token, the host name and the version). The tunnel lives until ctx ends, Close, or the transport drops; Done reports which.
func (*Client) Dial ¶
Dial opens one CONNECT stream to the host's loopback port and returns it as a net.Conn, for an http.Transport's DialContext or a raw relay.
It first takes one of the host's maxConns upstream slots. With all of them in use it WAITS, for at most DialWait, and then refuses with a *RefusedError whose Reason is max_conns (status 429) — so a page's burst of requests queues briefly instead of failing, and a host whose slots are held by paused readers fails fast enough to say so. A max_conns from the host itself (its backstop; a slot this side freed may still be winding down there) is retried within the same wait.
ctx bounds only the dial; the stream then lives until Close, the host's upstream closing, or the tunnel ending, and its slot is freed on Close. CloseWrite half-closes it. Deadlines are not supported (Set*Deadline returns errors.ErrUnsupported); Close is how to abort a stream.
func (*Client) Done ¶
func (c *Client) Done() <-chan struct{}
Done is closed when the tunnel has ended; Err then says why.
func (*Client) Err ¶
Err is why the tunnel ended (ErrClosed or ErrPeerUnresponsive), or nil while it is up.
func (*Client) RoundTrip ¶
RoundTrip sends one control request over the tunnel. A URL with no scheme or host is given "http://tunnel".
func (*Client) SetMaxConns ¶
SetMaxConns sets how many upstream connections Dial lets be open at once: the host's maxConns, from its config on the offer stream. n is clamped into 1..wire.MaxConns: below 1 becomes 1, not the default, because a limit this side believes is LARGER than the host's only turns waits into host refusals, while a smaller one is merely slower. Streams already open stay open; a Dial waiting for a slot sees a raised limit at once.
🔴 NEVER ABOVE THE FIRST: the limit must never exceed the maxConns the host's Serve was started with, which is fixed for the life of the tunnel (its HTTP/2 SETTINGS were sent at the start). The first call's value (the host's first config on the offer stream) is therefore a CEILING this client keeps itself: a later call may lower the limit, or raise it back up to that ceiling, never past it. A host whose maxConns grew must reconnect for the new value to take effect. ClientOptions.MaxConns is only the provisional limit before the first call, not the ceiling.
type ClientOptions ¶
type ClientOptions struct {
// PingInterval is the WebSocket ping interval; 0 means wire.PingInterval.
PingInterval time.Duration
// MaxConns is how many upstream connections Dial lets be open at once
// before it waits: the host's maxConns, which the gateway learns from the
// offer stream after the tunnel is up (SetMaxConns, which states the
// rule this must follow). 0 means wire.MaxConns, the cap; any other value
// is clamped into 1..wire.MaxConns as SetMaxConns does.
MaxConns int
// DialWait bounds how long Dial waits for a free upstream slot before
// refusing with max_conns; 0 means DefaultDialWait.
DialWait time.Duration
// contains filtered or unexported fields
}
ClientOptions configures the gateway end of a tunnel.
type HostOptions ¶
type HostOptions struct {
// MaxConns is the host's maxConns from previews.json: the most UPSTREAM
// connections (CONNECT streams) the tunnel carries at once. The control
// streams are not counted; they have ControlStreams of their own. 0 means
// wire.MaxConns; more than wire.MaxConns is refused.
MaxConns int
// PingInterval is the WebSocket ping interval; 0 means wire.PingInterval.
PingInterval time.Duration
// ErrorLog receives the HTTP/2 server's own errors; nil means the log
// package's standard logger.
ErrorLog *log.Logger
// contains filtered or unexported fields
}
HostOptions configures the host end of a tunnel.
type RefusedError ¶
RefusedError is Dial's error when the host answered the CONNECT with anything but 200. Reason is "" when the host gave none it may give for that status (wire.RefusalOf).
func (*RefusedError) Error ¶
func (e *RefusedError) Error() string