zmux

package module
v1.3.3 Latest Latest
Warning

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

Go to latest
Published: Nov 1, 2026 License: Apache-2.0 Imports: 39 Imported by: 2 modules, 1 package

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

zmux-go

CI Go Reference Release Go version License

zmuxquic zmuxh3 zmuxws

Go implementation of zmux: multiplexed, flow-controlled streams and datagrams over one or many reliable byte pipes.

zmux is wire-compatible with QMux (draft-ietf-quic-qmux-02): QUIC version 1 frames in size-prefixed records over TCP, TLS, WebSocket or any other reliable carrier. With a plain QMux peer a session is a plain single-pipe QMux session. Between zmux endpoints, transport parameters negotiate multipath (many pipes, per-frame spreading, failover with reinjection), lanes over multi-stream carriers, 0-RTT, resumption after every pipe is lost, and the base extensions: roles, GOAWAY, stream preambles, priorities and datagram flows.

Modules

Module Purpose
github.com/zmuxio/zmux-go core protocol, TCP/TLS/HTTP carriers, any message carrier
github.com/zmuxio/zmux-go/zmuxquic QUIC carriers (quic-go)
github.com/zmuxio/zmux-go/zmuxh3 HTTP/3 and WebTransport carriers
github.com/zmuxio/zmux-go/zmuxws WebSocket carriers

Client

conn, err := zmux.Dial(ctx, "tcp", "example.com:4433", nil)
// or: zmux.DialTLS(ctx, "tcp", "example.com:4433", tlsConf, nil)
if err != nil {
	return err
}
defer conn.Close()

st, err := conn.OpenStreamSync(ctx)
if err != nil {
	return err
}
if _, err := st.Write([]byte("hello")); err != nil {
	return err
}
if err := st.Close(); err != nil { // FIN: the write side is done
	return err
}
reply, err := io.ReadAll(st)

Client starts a session on a net.Conn you already have. Conn and Stream follow the quic-go method set; zmux.StreamConn turns a stream into a net.Conn.

Server

A Listener accepts sessions, and the pipes that later join them, from any net.Listener:

ln, err := net.Listen("tcp", ":4433")
if err != nil {
	return err
}
l := zmux.NewListener(&zmux.ListenerConfig{Config: cfg})
go l.Serve(ctx, ln) // for TLS: l.Serve(ctx, tls.NewListener(ln, tlsConf))

for {
	conn, err := l.Accept(ctx)
	if err != nil {
		return err
	}
	go func() {
		for {
			st, err := conn.AcceptStream(ctx)
			if err != nil {
				return
			}
			go func() {
				io.Copy(st, st) // echo
				st.Close()
			}()
		}
	}()
}

l.Shutdown(ctx, 0, "") stops accepting new sessions, ends every session gracefully while still taking their joins and resumptions, and then closes the listener; l.Close() refuses every carrier at once. zmux.Server serves a single connection without multipath.

In Config and the other configuration structs, the zero value of a field selects its stated default, a negative timeout means no timeout, other negative values are invalid unless the field gives them a meaning, and the Disable and No fields switch features off.

Closing

Conn.Close ends the session at once and discards data not yet sent, unlike net.Conn.Close. To let the peer read everything first:

ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
err := conn.Shutdown(ctx, 0, "")

Errors

_, err := st.Read(buf)
switch {
case errors.Is(err, zmux.ErrIdleTimeout):
	// the session timed out
case zmux.IsRetryable(err):
	// the peer did not process the stream: send it again
case errors.Is(err, net.ErrClosed):
	// the session ended for another reason
}

Multipath

Both endpoints set MaxPipes above 1 and a join secret; the server uses a Listener. The client adds pipes over other paths and follows them with NextEvent. The secret is PipeAuth.PSK, or PipeAuth.Exporter: the exporter of the innermost end-to-end handshake of the first pipe (zmux.Exporter: a carrier transform's own, or TLS that this process terminates, its handshake done or still running), read when the peer's parameters arrive. PipeAuth.DeferredPSK sends the PSK flag but takes the key later, for example once the application authenticated the peer over the session: conn.SetJoinSecret(psk) (once, at least 16 bytes) derives the join keys. Until then AddPipe fails with ErrJoinSecretPending, the peer's joins wait at most HandshakeTimeout (ConnectionStats.JoinSecretPending) and the session cannot resume. The peer may hold the same bytes as a static PSK. ListenerConfig.SessionConfig picks each new session's Config, for example Exporter where zmux.TerminatedTLS reports TLS ended here and DeferredPSK otherwise, or its ShapingLimits; Conn.SetShapingLimits replaces them while the session runs.

cfg := &zmux.Config{MaxPipes: 4, PipeAuth: zmux.PipeAuth{PSK: psk}}
conn, err := zmux.Dial(ctx, "tcp", primaryAddr, cfg)
if err != nil {
	return err
}
nc, err := net.Dial("tcp", backupAddr)
if err != nil {
	return err
}
p, err := conn.AddPipe(ctx, zmux.NetPipe(nc), zmux.PipeOptions{Label: "backup", SendStandby: new(true)})
if err != nil {
	return err
}
for {
	ev, err := conn.NextEvent(ctx)
	if err != nil {
		return err
	}
	if ev.Kind == zmux.EventPipeFailed && ev.Pipe == p.ID() {
		log.Println("backup path failed")
	}
}

The pointer fields of PipeOptions (SendPriority, SendStandby, Weight) are nil to follow the peer's request or the default; a set value, zero included, wins, so Weight: new(uint64(0)) excludes the pipe from spreading. Probation is the base of a pipe's probation (zero: the session's Config.SchedulerParams.Probation, whose zero derives it from the RTT and the pipe's history); NoProbation turns it off, and both exist in SchedulerParams too. PipeStats reports per-pipe loss: BytesLost and RecordsLost when a pipe fails, BytesRetransmitted and LossRate from the carrier's own retransmissions; see the godoc for their exact definitions.

Liveness can change while a session runs: Conn.SetLiveness replaces the keep-alive period and the failure-detection and probe settings as a whole (zero fields are the defaults, Conn.Liveness returns the values in effect), Pipe.SetLiveness and ClearLiveness set or drop a pipe's own. A pipe already suspect keeps the dead timeout it turned suspect under. Conn.RaiseIncomingStreams raises the incoming stream limits, for example after the peer has authenticated; the limits only grow.

WebSocket

zmuxws carries one zmux record per binary message (FramingRecords), so proxies that re-chunk the byte stream cannot break records. The subprotocol is the application protocol identifier: qmux-02 by default, qmux-02.<application> or an application's own identifier, each also accepted as its draft-01 alias.

// server: upgrades go to l; other requests, and those the admission
// does not accept, to Next
h, err := zmuxws.Handler(l, &zmux.HTTPOptions{Next: site})
http.Handle("/zmux", h)

// client
conn, err := zmuxws.Dial(ctx, "wss://example.com/zmux", nil, nil)

Nothing is answered before a request is accepted: a request that is not a WebSocket upgrade, or offers no accepted subprotocol, goes to Next, and the admission decides on the upgrade request's head. A client's credential travels in the upgrade request: Dial presents Config.Credential and DialPipe DialOptions.Credential, for a PrefixAuth in its Zmux-Prefix-Auth field, which PrefixAuthVerifier.Decide checks. DialPipe opens a further pipe, with the Zmux-Pipe-Join field of a Reservation for an out-of-band join, and zmuxws.Pipe adapts a WebSocket connection established otherwise. A close frame ends a pipe gracefully; an aborted pipe closes the connection without one.

A carrier exposes the TLS this process terminates beneath it (ConnectionState: the client's wss connection, the server's request TLS, shared by the WebSocket streams of one HTTP/2 connection), so PipeAuth.Exporter and CarrierBound work over wss (zmux.TerminatedTLS reports whether a carrier has such TLS). Over ws, or behind a proxy that terminates TLS, there is none and both fail, unless a carrier transform with its own handshake supplies the exporter. Only the exporter binding or a client that pins the server proves the TLS end to end.

HTTP exchanges

Where a long-lived HTTP request does not survive the path (CDNs and reverse proxies that buffer whole bodies, HTTP/1.0 hops, request duration limits, caches), an exchange carrier builds one zmux carrier out of a sequence of short POST requests. The server mounts a handler in front of its Listener:

h, err := zmux.NewHTTPExchangeHandler(l, &zmux.HTTPExchangeConfig{PSK: psk})
if err != nil {
	return err
}
defer h.Close()
http.Handle("/x/", h)

and the client opens the carrier with the same PSK:

p, err := zmux.HTTPExchangePipe(ctx, client, "https://example.com/x/{instance}/{nonce}",
	&zmux.HTTPExchangeConfig{PSK: psk})
if err != nil {
	return err
}
conn, err := zmux.Start(ctx, p, zmux.RoleClient, cfg) // or conn.AddPipe(ctx, p, opts)

{instance} is the same in every request of a carrier (for load-balancer stickiness) and {nonce} differs in every request (cache busting; without it a query parameter is added). DownURL sends DOWN requests to another template (scheme, host, port and path may all differ, through other intermediaries); UP and CLOSE requests use the first. A carrier's state lives in one server process: with several backends, route every request of a carrier to the same one, for example by hashing {instance}. The default piece size keeps every body at most 1,000,000 bytes after the body encoding, below the 1 MiB request body limit common on reverse proxies; each end accepts pieces up to 1 MiB, or its own piece size when larger. A DOWN body over the client's limit fails the carrier, and an UP body over the server's is not taken and fails the carrier at the client's deadline. Requests are numbered, idempotent and authenticated, so lost, repeated, reordered and cached exchanges are recovered. Every request carries its send time and a random nonce: the server takes a request only within MaxClockSkew of its own clock and only once per (carrier ID, nonce), so both ends need roughly synchronized clocks. Requests it does not take go to Next (http.NotFound without one), with their body; HTTPExchangeConfig documents the timers, sizes and limits and their defaults. Keep the server's HoldTime below every intermediary's response timeout, and the client transport's MaxIdleConnsPerHost at least DownRequests+UpRequests.

The exchange MACs authenticate both ends with the PSK and bind each response to its request, but they do not encrypt. A PSK is required; AllowInsecure runs the carrier without one (tests and protected networks), and the carrier ID then is a bearer secret. When TLS is terminated by a proxy or CDN, that intermediary can read the carrier.

Behind a reverse proxy or CDN

Which HTTP carriers pass depends on the path: a front that buffers request bodies passes downlinks but not streaming uplinks, one that buffers whole bodies passes only the exchange carrier, and some fronts pass WebSocket only. The server can serve every kind on one target, and the client can choose among them.

One endpoint. HTTPEndpoint classifies each request by its head (ClassifyHTTP) and hands it to the adapter of its class; requests that are not carriers, and those an adapter's admission does not take, go to the host's handler with their body:

stream, err := zmux.NewHTTPHandler(l, &zmux.HTTPOptions{Next: site, Trusted: trusted})
ex, err := zmux.NewHTTPExchangeHandler(l, &zmux.HTTPExchangeConfig{PSK: psk, Next: site, Trusted: trusted})
ws, err := zmuxws.Handler(l, &zmux.HTTPOptions{Next: site, Trusted: trusted})
http.Handle("/zmux", &zmux.HTTPEndpoint{Stream: stream, Exchange: ex, WebSocket: ws, Next: site})

Its WebTransport field takes a WebTransport handler such as zmuxh3.Handler for the WebTransport sessions served on the same target.

Choosing a carrier. DialMode takes a mode: ExplicitMode(c) uses one kind and reports its failure as it is; AutoMode(c...) tries candidates in order of preference and keeps the first whose peer answers within a short timer, without early data and without racing them. With Config.MaxPipes above 1 it establishes the session on the most robust kind (the exchange carrier unless a kind is known to work) and moves the session to preferred kinds by joining them as further pipes, without a second session. A CarrierCache in ModePolicy remembers per server and local network which kinds worked; a kind that failed, or dropped soon after it was chosen, is skipped until its backoff expires. Each try and the choice are reported as EventCarrierCandidate and EventCarrierChosen, and in ConnectionStats. CarrierCache.Snapshot and Restore carry what it knows across restarts as versioned JSON. The moves to preferred kinds are a PipePool with a Mode: each member is dialed over the most robust kind available and rotated to a preferred one, make before break, so MaintainPipes can keep a session's further pipes on the best kind a path passes.

conn, err := zmux.DialMode(ctx, zmux.AutoMode(
	zmuxws.Candidate("wss://example.com/zmux", nil),
	zmux.StreamingCandidate(client, "https://example.com/zmux", nil),
	zmux.SplitCandidate(client, "https://example.com/zmux", nil),
	zmux.ExchangeCandidate(client, "https://example.com/zmux", &zmux.HTTPExchangeConfig{PSK: psk}),
), cfg, &zmux.ModePolicy{Cache: cache, Key: "example.com|" + network})

zmuxquic.Candidate and zmuxh3.WebTransportCandidate add the kinds a client can use when it reaches the server directly, and zmuxh3.HTTP3Candidate a streaming request over HTTP/3. A carrier kind describes only this end's hop, not what lies beyond its first peer.

Client addresses. Behind a proxy every carrier comes from the proxy's address. TrustedProxies names the proxies whose report of the client address is believed: its Listener wraps a net.Listener that receives the PROXY protocol from them, and HTTPOptions.Trusted (and HTTPExchangeConfig.Trusted) reads the forwarding header field they set. The reported address is then the source that admissions see and that the listener's per-source limits count; the same report from any other peer is ignored.

trusted := &zmux.TrustedProxies{Prefixes: []netip.Prefix{netip.MustParsePrefix("127.0.0.1/32")},
	Header: "X-Forwarded-For"}

TLS at the proxy. The server then sees no TLS: prefix tokens are unbound, joins need PipeAuth.PSK, and the exchange carrier can be read by the proxy. Keep the hop from the proxy to the server local or encrypted.

Proxy configuration. A location that passes every kind, in nginx syntax:

map $http_upgrade $connection_upgrade {
    default upgrade;
    ''      '';
}

location /zmux {
    proxy_pass http://127.0.0.1:8080;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;          # WebSocket
    proxy_set_header Connection $connection_upgrade;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_request_buffering off;   # stream uplinks as they arrive
    proxy_buffering off;           # downlinks also send X-Accel-Buffering: no
    proxy_read_timeout 300s;       # above the session's keep-alive
    proxy_send_timeout 300s;
    client_max_body_size 1m;       # exchange bodies stay within 1,000,000 bytes
}
  • Full duplex: a bidirectional request carrier needs both bodies forwarded at once, which an HTTP/1.1 hop does not guarantee. Pass it over HTTP/2 without TLS (grpc_pass grpc://127.0.0.1:8080; in a server whose listener has http2 on), and let the server accept HTTP/2 by prior knowledge:

    srv := &http.Server{Addr: "127.0.0.1:8080", Handler: endpoint, Protocols: new(http.Protocols)}
    srv.Protocols.SetHTTP1(true)
    srv.Protocols.SetUnencryptedHTTP2(true)
    
  • Early data: keep ssl_early_data off, or forward its marker with proxy_set_header Early-Data $ssl_early_data;: the adapters answer a carrier request that carries Early-Data: 1 with 425 (Too Early), and the proxy repeats it after its handshake. An HTTP/3 server with quic.Config.Allow0RTT hands requests over before the handshake completes; the adapters answer those carrier requests 425 as well.

  • Idle limits: proxies end requests that stay silent (60 s by default for the read and send timeouts, 30 s to 125 s for a CDN's response): keep Config.KeepAlivePeriod (15 s by default, at most half the idle timeout; negative turns it off) and, with multipath, the probe interval below the shortest limit on the path, and the exchange server's HoldTime below the CDN's response timeout.

Admission

An Admission is configured on the listener (ListenerConfig.Admission) and decides on every carrier of it before anything is sent on it, whatever entry point took it: Listener.Serve and HandlePipe, NewHTTPHandler, the exchange handler, zmuxws.Handler, zmuxh3.Handler and zmuxquic.Serve. Every entry runs the same steps: the carrier takes a slot of its source (MaxPendingPerSource) before its outer handshake (TLS, an HTTP upgrade, QUIC), the admission reads up to Peek bytes (on a message-framed carrier its first message) and calls Decide with them and the carrier's metadata (CarrierInfo: its Source and Peer, TLS state, HTTP request), then WrapPipe runs and the carrier is classified. Decide gets a context that ends with what remains of PeekTimeout and when the listener stops. It accepts the carrier (without the bytes it skips), hands it with every byte read to the fallback of its kind (ListenerConfig.Fallback for byte streams, HTTPOptions.Next for HTTP, the fallback of zmuxquic.Serve), stalls it, or closes it; VerdictMore reads a longer prefix (up to MaxPeek) and decides again, and Decision.Variant labels the carrier, counted per label in Listener.VariantStats (one of a few host constants, never derived from the peer's bytes; past MaxAdmissionVariants labels share one bucket). A source holds at most MaxPendingPerSource - 1 stalled carriers, and a stall lasts the same duration for every carrier from one source during the listener's lifetime (Listener.StallDuration). ListenerStats.Admission counts the outcomes. An adapter with its own accept loop takes a carrier with Listener.Arrive (AdmitUpgrade for an HTTP upgrade) and hands it on with Arrival.HandlePipe. PrefixAuth is one Decide: a carrier starts with a token of PrefixTokenLen bytes, optionally bound to its TLS handshake; a carrier decided on its request head (a WebSocket or WebTransport upgrade, an HTTP request carrier without a body such as a downlink GET) carries it in the Zmux-Prefix-Auth request field instead (HeaderPrefixAuth, 43 characters of base64url). The same Admission serves both:

auth := &zmux.PrefixAuth{Key: key, Slot: 30 * time.Second, Skew: 1, BindTLS: true}
v, err := zmux.NewPrefixAuthVerifier(auth)
l := zmux.NewListener(&zmux.ListenerConfig{Config: cfg,
	Admission: &zmux.Admission{Peek: zmux.PrefixTokenLen, Decide: v.Decide}, Fallback: fallback})
go l.Serve(ctx, tls.NewListener(ln, tlsConf))

// client: Config.Credential is presented by the dialers
conn, err := zmux.DialTLS(ctx, "tcp", addr, tlsConf, &zmux.Config{Credential: auth})

A Credential is the client side of an admission: Prefix gives the first bytes of a carrier, Header the request field of a carrier decided on its request head, each from the carrier's metadata (CarrierInfo, with its TLS state for a binding). Client, Dial, DialTLS, zmuxquic.Dial and Client, zmuxws.Dial and zmuxh3.Dial present Config.Credential; the pipe dialers for joins take theirs in zmuxws.DialOptions.Credential, zmuxquic.NewPool, zmuxh3.NewPool and zmuxh3.DialSession; HTTPPipe and HTTPSplitPipe take one (unbound: the request's connection is not known in advance), and PresentPipe presents one on any other byte-stream pipe.

A split bootstrap (HTTPSplitPipe, SplitCandidate) holds its first half in a pairing slot until the other half arrives or the handshake timeout ends: 64 slots per listener and 8 per source (SPEC.md 6.1.1), counted by the source that MaxPendingPerSource counts (an IPv6 client by its /64). Without an Admission, a few sources can keep those slots full and delay other clients' split bootstraps; serve a split bootstrap that the open Internet reaches with an Admission, such as PrefixAuth.

ListenerConfig.AnswerUnknownJoins (off by default) answers an admitted join for a session this instance does not hold with ZMUX_RESUME_FAILED, so a suspended client fails at once instead of at its resume timeout. Leave it off where a load balancer can route a join to another instance with the same InstanceID.

Carrier transforms

A transform (compression, a byte transform, a handshake of its own) wraps a carrier on both ends with the public API alone: the client in a Candidate's Dial (or before Start, AddPipe), the server in ListenerConfig.WrapPipe, after an Admission that tells its first bytes from a zmux first record (ClassifyFirstBytes, VerdictMore, Decision.Variant). A batch of records is one write on the wrapped half (one WriteMessages on a message-framed MessageBatchWriter). The halves offer capabilities as interfaces (CloseWriter, Aborter, ConnectionStater, KeyingMaterialExporter, EarlyClientCarrier, ResponseHeaderer, ...); a transform forwards a lower one only where its meaning survives. A transform whose first message carries the client's first flight uses EarlyData.HoldFirstFlight with Conn.ReleaseFirstFlight and reports the server's verdict as carrier early data (EarlyClientCarrier.SendsEarlyData); ReplayFilter is the single-use cache for its nonces, checked only after the nonce and its timestamp were authenticated together. ResponseHeaderer metadata is unauthenticated and never decides authentication. PipeIO.Variant labels the carriers in events, statistics, shaping and CarrierCache (with CarrierCache.Report for outcomes the host learns later). examples/xorpipe is a complete example.

QUIC

conn, err := zmuxquic.Dial(ctx, "example.com:4433", tlsConf, nil, nil)

On the server, zmuxquic.Serve(ctx, ln, l, nil) hands the streams of a QUIC listener to a zmux.Listener; zmuxquic.ServeConn serves one QUIC connection the caller already accepted or dialled, such as one made by hole punching. zmuxh3.Dial and zmuxh3.Serve do the same for WebTransport sessions.

The default dialer of zmuxquic.Dial and NewPool binds udp4 or udp6 by the destination's address family. Native QUIC 0-RTT streams are currently created only after the handshake completes; zmux's own replayable startup and resumption are not affected. A quic.Conn passed to Client or OpenPipe stays owned by the caller.

Datagram channels

QUIC, HTTP/3 and WebTransport carriers have an unreliable datagram service of their own besides the stream that is the pipe. When both endpoints enable datagrams and support it, a datagram that fits is sent there instead of in a record, so a lost packet loses that datagram rather than delaying every later one behind the stream's retransmission. Nothing changes for the application: the same calls, sizes and queues; larger datagrams, pipes whose records are shaped, and peers without the channel use records. ConnectionStats counts the datagrams that went on channels (DatagramsSentChannel, DatagramsReceivedChannel), and zmuxquic.ChannelDropped the QUIC datagrams that named no attached pipe.

  • QUIC: the connection's QUIC datagrams, each naming its pipe by stream ID, so several pipes and sessions share a connection. QUICConfig enables them; a connection that carries pipes leaves its datagrams to zmux.
  • WebTransport: the session's datagrams, named the same way.
  • HTTP/3: the HTTP Datagrams of a bidirectional carrier's request stream. NewHTTP3Server enables them (HTTP3Handler wraps the handler of any other HTTP/3 server). Pipes opened with an http.Client, as HTTP3Candidate does, keep datagrams in records.

A carrier of another kind offers its own channel by implementing zmux.DatagramChannel on a half of its PipeIO; zmux.ChannelDemux routes the datagrams of a connection shared by several pipes.

Pool policies

PipePool.Policy and CarrierPool.Policy take a zmux.PoolPolicy. machine.PoolPolicy (package shaping/machine) builds one from JSON:

{
  "count": {"const": 2},
  "dial_after": [{"const": 1}, {"range": [5, 10]}],
  "retire": [{"metric": "age", "above": {"range": [1800, 3600], "scope": "pipe"}}]
}

Every field is optional; an absent field keeps the pool's own value, and an unknown field or metric fails construction. Values have the form and validation of definition values; times are in seconds.

  • count is rounded; below 1 it is 1.
  • dial_after[k] is the delay after the last dial when k dials in a row failed; the last entry applies to any higher number.
  • dial_jitter, 0 to below 1, shortens each dial_after wait by a random fraction of up to it; it needs dial_after.
  • retire lists a member when one rule's metric is strictly greater than its threshold; members are listed in view order, each once. Metrics: age, idle (seconds), pipes, bytes_sent, bytes_received, bytes (their sum). A rule's jitter, 0 to below 1, lowers its threshold by a random fraction of up to it, drawn once per member.
  • probe_interval is the probe interval of the pipes the pool dials; 0 turns their idle probes off. probe_jitter, 0 to below 1, is their probe jitter and needs probe_interval.
  • Scopes: each (or none) draws at every decision, shared once per policy, pipe once per member ID while the member is in the view. pipe is accepted only in retire thresholds.

Recheck is set to the earliest time at which an age or idle rule would hold for a member not retired, or at which dial_after after the last dial elapses; 0 when there is neither. Byte and pipe rules do not set it. Pools decide again no later than Recheck (at least zmux.MinRecheck, 10 ms) in addition to their own triggers.

Options.NewSource sets the random source; Decide does not block.

More

The package documentation and its examples cover datagrams, stream preambles and priorities, early data and its retry, splicing streams between sessions, lanes, nested sessions and the scheduler. The protocol is specified in the zmux specification repository.

zmuxtest is experimental test support (a misbehaving reverse proxy and a carrier-cutting relay), outside the API stability promise.

Testing

go test -race ./...

Run it in each module directory. The root go.work makes the sub-modules build against the local root module; see RELEASING.md for the release order.

License

Apache-2.0

Documentation

Overview

Package zmux multiplexes streams and datagrams over one or many reliable byte pipes. It speaks QMux (so a plain QMux peer interoperates) and, with a zmux peer, adds stream preambles, priorities, acknowledged pipes, multipath with failover and resume, lanes over multi-stream carriers, and nested sessions.

Sessions and streams

A client dials with Dial (TCP) or DialTLS, or starts a session on a connection it already has with Client. A server serves a net.Listener with a Listener (Listener.Serve) and takes the sessions from Listener.Accept; the Listener also accepts the pipes that join its sessions, so it is the server for multipath and resume. Server starts a single-pipe session on one accepted connection. Start takes any carrier (PipeIO, for example a WebSocket connection with FramingRecords) and an explicit Role, and Listener.HandlePipe or NewHTTPHandler accept any carrier. An Admission on the Listener (ListenerConfig.Admission, PrefixAuth) decides on every carrier before anything is sent on it, whatever entry point took it, and a Credential is what a client presents for it (Config.Credential, PresentPipe). HTTPExchangePipe and HTTPExchangeHandler build a carrier out of short HTTP requests for paths that buffer or cut long ones; they authenticate but do not encrypt, so a proxy or CDN that terminates TLS can read such a carrier. The sub-modules zmuxquic and zmuxh3 carry sessions over QUIC, HTTP/3 and WebTransport.

A carrier transform (a byte transform, compression, a handshake of its own) wraps carriers with the public API: a Candidate's Dial on the client, ListenerConfig.WrapPipe on the server, behind an Admission that tells its first bytes from a zmux first record (ClassifyFirstBytes, VerdictMore, Decision.Variant). Its halves offer the optional capabilities that PipeIO lists (KeyingMaterialExporter for its own exporter, EarlyClientCarrier for a first flight that the server may refuse, with EarlyData.HoldFirstFlight and Conn.ReleaseFirstFlight); ReplayFilter is a single-use cache for its nonces.

The Conn and Stream methods follow quic-go: OpenStream[Sync], AcceptStream, Read, Write, Close (FIN), CancelRead, CancelWrite, deadlines, SendDatagram and ReceiveDatagram. StreamConn gives a stream the net.Conn interface.

Blocking: calls that wait take a context.Context (OpenStreamSync, AcceptStream, Ping, Shutdown, AddPipe, NextEvent, ...) or honour the stream's deadlines (Read, Write). Close, CloseWithError, CancelRead, CancelWrite and Pipe.Close never block; Wait blocks until the session and all its goroutines ended. Conn.Context and Stream.Context are the session's context.

Closing: Conn.Close ends the session at once and discards data not yet sent; Conn.Shutdown lets open streams finish first. Listener.Shutdown does the same for every session of a listener.

Ownership: a Stream handle that is garbage-collected without being closed resets and stops its stream, so keep it while it is in use. A net.Conn given to Client or Server and a PipeIO given to Start, AddPipe or HandlePipe belong to zmux from then on, which closes each half exactly once, unless the call fails with ErrInvalidConfig before taking it. A Chunk from ReadChunk is released exactly once, by Release or by WriteChunk.

Events

Pipe changes and other session events (EventKind) can be read with Conn.NextEvent, or received with a Config.Tracer; both are optional and bounded, and the current state is always available from Conn.PipeStats and Conn.ConnectionState.

Errors

A session's end is one of *ApplicationError, *TransportError, *IdleTimeoutError, *HandshakeTimeoutError, *EarlyDataRejectedError, *ResumeTimeoutError or *PipesLostError. Every one matches net.ErrClosed with errors.Is; the last five also match their sentinel (ErrIdleTimeout, ErrHandshakeTimeout, ErrEarlyDataRejected, ErrResumeTimeout, ErrPipesLost), the timeouts also os.ErrDeadlineExceeded, and the two that a lost pipe caused unwrap to that pipe's error. A stream the peer reset or stopped gives a *StreamError. IsRetryable reports streams the peer did not process (ErrRejected, ErrGoingAway, ErrEarlyDataRejected), which can be sent again. Calls fail with ErrStreamClosed, ErrNotNegotiated, ErrNotEstablished, ErrTooLate, ErrInvalidConfig, ErrPipeGone or ErrNoDecision where their documentation says so.

Names

Constants carry the name of their type, or a short form of it, as a prefix: Role (RoleClient), Direction (DirSendOnly), Framing (FramingRecords), Urgency (UrgencyDefault), EventKind (EventPipeJoined), OutboundState (OutboundActive), Endpoint (EndpointLocal), Transport for transport error codes (TransportProtocolViolation) and Stream for stream error codes (StreamCancelled).

Rates are float64 bytes per second throughout (PickPipe.Rate, PipeStats.DeliveryRate, Event.DeliveryRate, CapacityFloor.Rate); memory budgets and usage are int64 bytes.

Configuration

Settings: the zero value of a field selects its default, stated in the field's documentation; for timeouts and limits it is a safe bound unless the field says otherwise. A negative timeout means no timeout, as for http.Server.IdleTimeout. Other negative values are an error unless the field gives them a meaning.

The fields that give negative values a meaning follow the standard library: KeepAlivePeriod turns keep-alive off (net.Dialer.KeepAlive), SchedulerParams.ProbeInterval and StandbyProbe and PipeOptions.ProbeInterval turn probes off (net.KeepAliveConfig), and HTTPExchangeConfig.Coalesce sends at once (httputil.ReverseProxy.FlushInterval). A memory budget is lifted with NoMemoryLimit. Other settings that turn something off are Disable and No fields, as in net/http (NoIncomingStreams, NoProbeJitter, PoolDecision.DisableIdleProbe, QualityBand.NoMinInterval, shaping.Limits.NoPadding, ...). Zero values that are not a safe bound: shaping.Limits (zero is unbounded; the session's other limits still apply), PipePool.Rotate (zero rotates nothing) and Config.ResumeTimeout (zero is no resume). Errors are ErrInvalidConfig; NewListener panics.

Multipath needs MaxPipes above 1 and a PipeAuth (PSK, DeferredPSK with Conn.SetJoinSecret, or Exporter); without a secret, joins are possible only with PipeAuth.AllowInsecure, meant for tests and protected networks.

Time

Config.Clock (a timeshim.Clock; nil is the host's monotonic clock) is the session's time source: its timers, deadlines, RTT and rate estimates, and the Redial and MaintainPipes waits run on it, so a timeshim.Fake drives a session deterministically. Carrier read and write deadlines of net.Conn, Listener and endpoint timers (first record, pairing, carrier upgrade, the exchange carrier) and the transports of the QUIC adapters (zmuxquic, zmuxh3: quic-go's loss recovery, idle and handshake timers) stay on the host clock.

Example (Tcp)

Example_tcp serves zmux on a TCP listener and dials it. The Listener is the server for every kind of client, including those that later join more pipes to their session.

package main

import (
	"context"
	"fmt"
	"io"
	"net"
	"time"

	"github.com/zmuxio/zmux-go"
)

// echo answers every stream of conn with what it read, until conn ends.
func echo(ctx context.Context, conn *zmux.Conn) {
	for {
		st, err := conn.AcceptStream(ctx)
		if err != nil {
			return
		}
		go func() {
			_, _ = io.Copy(st, st)
			_ = st.Close()
		}()
	}
}

// roundTrip opens a stream, sends msg, finishes the stream and returns the
// answer.
func roundTrip(ctx context.Context, conn *zmux.Conn, msg string) (string, error) {
	st, err := conn.OpenStreamSync(ctx)
	if err != nil {
		return "", err
	}
	if _, err := st.Write([]byte(msg)); err != nil {
		return "", err
	}
	if err := st.Close(); err != nil {
		return "", err
	}
	b, err := io.ReadAll(st)
	return string(b), err
}

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	// Server.
	ln, err := net.Listen("tcp", "127.0.0.1:0")
	if err != nil {
		fmt.Println(err)
		return
	}
	l := zmux.NewListener(nil)
	go func() { _ = l.Serve(ctx, ln) }()
	go func() {
		for {
			conn, err := l.Accept(ctx)
			if err != nil {
				return
			}
			go echo(ctx, conn)
		}
	}()

	// Client.
	conn, err := zmux.Dial(ctx, "tcp", ln.Addr().String(), nil)
	if err != nil {
		fmt.Println(err)
		return
	}
	reply, err := roundTrip(ctx, conn, "hello over TCP")
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(reply)

	// Graceful end: the client, then every session of the listener.
	_ = conn.Shutdown(ctx, 0, "")
	_ = l.Shutdown(ctx, 0, "")
}
Output:
hello over TCP
Example (WebSocket)

Example_webSocket runs a session over a message-framed carrier such as WebSocket, through the adapter wsPipe above; an in-memory connection stands in for the WebSocket library here.

ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
ca, sa := memWebSocketPair()

done := make(chan *zmux.Conn, 1)
go func() {
	server, err := zmux.Start(ctx, wsPipe(sa), zmux.RoleServer, nil)
	if err != nil {
		done <- nil
		return
	}
	go echo(ctx, server)
	done <- server
}()
client, err := zmux.Start(ctx, wsPipe(ca), zmux.RoleClient, nil)
if err != nil {
	fmt.Println(err)
	return
}
server := <-done
if server == nil {
	_ = client.Close()
	fmt.Println("server failed")
	return
}
defer closeBoth(client, server)

reply, err := roundTrip(ctx, client, "hello over messages")
if err != nil {
	fmt.Println(err)
	return
}
fmt.Println(reply)
Output:
hello over messages

Index

Examples

Constants

View Source
const (
	// DefaultKeepAlivePeriod is the default Config.KeepAlivePeriod.
	DefaultKeepAlivePeriod = time.Duration(core.DefaultKeepAlive)
	// DefaultMaxIdleTimeout is the default Config.MaxIdleTimeout.
	DefaultMaxIdleTimeout = time.Duration(core.DefaultIdleTimeout)
	// DefaultProbeJitter is the default SchedulerParams.ProbeJitter.
	DefaultProbeJitter = core.DefaultProbeJitter
	// MaxRedialBackoff caps the wait between Config.Redial calls, the
	// built-in backoff and RedialPolicy's DialAfter alike.
	MaxRedialBackoff = 30 * time.Second
	// DefaultMaxBackoff is the default PipePool.MaxBackoff of MaintainPipes.
	DefaultMaxBackoff = 60 * time.Second
)

Session defaults, which the zero values of Config fields select.

View Source
const (
	JoinAuthReasonMAC          = JoinAuthReason(core.JoinAuthMAC)             // a token without carrier binding
	JoinAuthReasonCarrierBound = JoinAuthReason(core.JoinAuthMACCarrierBound) // a carrier-bound token
)
View Source
const (
	HeaderJoin = "Zmux-Pipe-Join"
	HeaderPair = "Zmux-Pipe-Pair"
)

HTTP carriers: a request body carries the up direction, a response body the down direction. HTTP/2 and HTTP/3 requests (and HTTP/1.1 with full duplex) carry both; a split bootstrap pairs an uplink POST and a downlink GET by the Zmux-Pipe-Pair header (SPEC.md 6.1.1), and a pipe that cannot write first joins out of band with Zmux-Pipe-Join (MULTIPATH.md 5.3).

View Source
const (
	OutboundNone     = OutboundState(core.OutNone)
	OutboundJoining  = OutboundState(core.OutJoining)
	OutboundActive   = OutboundState(core.OutActive)
	OutboundSuspect  = OutboundState(core.OutSuspect)
	OutboundDraining = OutboundState(core.OutDraining)
	OutboundFailed   = OutboundState(core.OutFailed)
	OutboundClosed   = OutboundState(core.OutClosed)
)
View Source
const (
	InboundNone    = InboundState(core.InNone)
	InboundJoining = InboundState(core.InJoining)
	InboundOpen    = InboundState(core.InOpen)
	InboundEnded   = InboundState(core.InEnded)
)
View Source
const (
	PrefixTokenLen = prefixNonceLen + prefixTagLen

	// PrefixAuthExporterLabel is the TLS exporter label of the binding.
	PrefixAuthExporterLabel = "EXPORTER-zmux-prefix-auth"
	// HeaderPrefixAuth is the request field of the header form.
	HeaderPrefixAuth = "Zmux-Prefix-Auth"
)

Prefix authentication tokens: a carrier starts with a token of PrefixTokenLen bytes, a random Nonce and a MAC over a time slot, an optional binding to the carrier's TLS handshake and the Nonce. Every byte of a token is random or a MAC output. A carrier decided on its HTTP request head (WebSocket, WebTransport) carries the token in a request header field instead, HeaderPrefixAuth by default, as base64url without padding.

View Source
const DefaultALPN = "qmux-02"

DefaultALPN is the default application protocol identifier, for ALPN and for carriers that negotiate it otherwise, such as a WebSocket subprotocol: QMux draft-02 with the application agreed out of band (SPEC.md 6.2). Applications with an identity of their own use "qmux-02.<application>" or an identifier of their own.

View Source
const DefaultHTTPRedirects = 5

DefaultHTTPRedirects is the number of redirects an HTTP carrier request follows unless its client's CheckRedirect decides (or, for a WebSocket, its dial options set another bound).

View Source
const DefaultMaxRecordSize = wire.DefaultMaxRecordSize

DefaultMaxRecordSize is the max_record_size in effect while it is absent (16382 bytes): records are built at most this large before the peer's parameters arrive, and always on a TLS carrier.

View Source
const MaxAdmissionVariants = 64

MaxAdmissionVariants bounds the distinct Decision.Variant values a listener counts apart; the outcomes of further values are counted in one VariantStat with Overflow set. Variants are meant to be a few constants of the host, never derived from what the peer sent.

View Source
const MaxFirstBytes = 5

MaxFirstBytes is the most bytes ClassifyFirstBytes needs.

View Source
const MaxInstanceIDLen = 8

MaxInstanceIDLen bounds ListenerConfig.InstanceID so that at least 8 random bytes remain in the 16-byte session locator.

View Source
const MaxRecordSize = wire.MaxRecordSize

MaxRecordSize is the largest record zmux accepts (its max_record_size): with FramingRecords, the largest message a carrier needs to deliver.

View Source
const MaxWriteOverhead = 65535

MaxWriteOverhead is the largest PipeIO.WriteOverhead.

View Source
const MinRecheck = 10 * time.Millisecond

MinRecheck is the shortest wait a pool applies to PoolDecision.Recheck.

View Source
const NoMemoryLimit int64 = -1

NoMemoryLimit as a MemoryBudget (Config or ListenerConfig) leaves the memory unlimited; it is the only value that lifts a size limit.

Variables

View Source
var (
	// ErrHandshakeTimeout reports that the peer's transport parameters did not
	// arrive in time (*HandshakeTimeoutError).
	ErrHandshakeTimeout = errors.New("zmux: handshake timeout")
	// ErrEarlyDataRejected reports that the peer rejected early data and
	// processed none of it (*EarlyDataRejectedError).
	ErrEarlyDataRejected = errors.New("zmux: early data rejected")
	// ErrIdleTimeout reports that the idle timeout closed the session
	// (*IdleTimeoutError).
	ErrIdleTimeout = errors.New("zmux: idle timeout")
	// ErrResumeTimeout reports that a suspended session was not resumed in time
	// (*ResumeTimeoutError).
	ErrResumeTimeout = errors.New("zmux: resume timeout")
	// ErrResumeFailed reports that a session closed with ZMUX_RESUME_FAILED
	// (*TransportError): among others, a suspended session whose resume
	// join the listener answered with it, as it holds no session for the
	// locator (ListenerConfig.AnswerUnknownJoins).
	ErrResumeFailed = errors.New("zmux: resume failed")
	// ErrPipesLost reports that the session lost its pipes and could not resume
	// (*PipesLostError).
	ErrPipesLost = errors.New("zmux: pipes lost")
)

Sentinel errors of session ends. Each session-end type matches its sentinel with errors.Is, so errors.Is(err, ErrIdleTimeout) works on any error of the session or of a call that failed because the session ended.

View Source
var (
	// ErrStreamClosed is returned for operations on a direction the
	// application closed itself.
	ErrStreamClosed = errors.New("zmux: stream closed")
	// ErrNotNegotiated is returned for features the session does not use.
	ErrNotNegotiated = errors.New("zmux: feature not negotiated")
	// ErrNotEstablished is returned for calls that need the peer's
	// parameters before they arrived.
	ErrNotEstablished = errors.New("zmux: session not established")
	// ErrRejected reports a stream the peer did not process (ZMUX_REJECTED
	// or at or above a GOAWAY watermark); it is retryable.
	ErrRejected = errors.New("zmux: stream rejected")
	// ErrGoingAway reports an open after local shutdown or the peer's GOAWAY; it is retryable.
	ErrGoingAway = errors.New("zmux: going away")
	// ErrTooLate is returned for settings that must precede the first frame.
	ErrTooLate = errors.New("zmux: too late: the stream's first frame was sent")
	// ErrInvalidConfig wraps configuration errors.
	ErrInvalidConfig = errors.New("zmux: invalid configuration")
	// ErrMessageTooLarge is returned by MessageLimitReader.ReadMessageLimit
	// for a message above its limit.
	ErrMessageTooLarge = errors.New("zmux: message too large")
	// ErrJoinSecretPending is returned by joins of a session whose
	// PipeAuth.DeferredPSK was not supplied yet (Conn.SetJoinSecret).
	ErrJoinSecretPending = errors.New("zmux: join secret pending")
	// ErrJoinSecretSet is returned by a second Conn.SetJoinSecret.
	ErrJoinSecretSet = errors.New("zmux: join secret already set")
	// ErrNoExporter is returned by Conn.ExportKeyingMaterial when the
	// bootstrap carrier has no keying material exporter.
	ErrNoExporter = errors.New("zmux: the carrier has no keying material exporter")
	// ErrPipeGone is returned by Pipe methods once the session no longer
	// knows the attachment.
	ErrPipeGone = errors.New("zmux: pipe gone")
	// ErrNoDecision is returned by ResolveDuplicate when no input of the
	// duplicate-session rule decides between the two sessions.
	ErrNoDecision = errors.New("zmux: the duplicate-session rule has no input that decides")
)

Errors of individual calls.

Functions

func ALPNAlias added in v1.3.2

func ALPNAlias(id string) (string, bool)

ALPNAlias returns the draft-01 alias of a configured identifier (SPEC.md 6.2), compared byte for byte: qmux-02 has the alias qmux-01, qmux-02.<application> has qmux-01.<application>, any other identifier that ends in -02 has the one that ends in -01, and any other identifier has none. A server accepts a configured identifier offered as it is or as its alias; a client may offer the aliases after its identifiers.

func AppendChannelDatagram added in v1.3.2

func AppendChannelDatagram(b []byte, withID bool, id uint64, data []byte) []byte

AppendChannelDatagram appends the channel datagram of one DATAGRAM frame with data, after the Pipe Stream ID id when withID (EXTENSIONS.md 6.8).

func CheckHTTPRedirect added in v1.3.2

func CheckHTTPRedirect(from *url.URL, method string, status int, location string) (*url.URL, error)

CheckHTTPRedirect decides whether a carrier request with method to from, answered with the redirect status and location, is repeated at the URL it returns, with the same method, fields and body. It refuses, with an *HTTPRedirectError, a redirect to another host name, from a secure scheme (https, wss) to an insecure one, to another port without a scheme upgrade, and a 301, 302 or 303 of a request other than GET unless it is a pure scheme upgrade (the same host, path and query over https). The schemes ws and wss count as http and https; the result keeps the family of from. status must satisfy IsHTTPRedirect.

func DefaultExchangePieceSize added in v1.3.2

func DefaultExchangePieceSize(base64 bool) int

DefaultExchangePieceSize returns the default UP and DOWN piece size: the largest whose bodies, with the longest header and after the body encoding (base64 or not), stay at most 1,000,000 bytes.

func HandleLane added in v1.3.0

func HandleLane(ctx context.Context, p PipeIO) error

HandleLane routes a stream that the peer opened on a lane-capable carrier connection, on an endpoint without a listener: its first record names the session by Lane Key. A stream that names no pipe is closed. It blocks until the lane ends.

func IsHTTPRedirect added in v1.3.2

func IsHTTPRedirect(status int) bool

IsHTTPRedirect reports whether status is a redirect an HTTP carrier considers (301, 302, 303, 307, 308).

func IsRetryable added in v1.3.0

func IsRetryable(err error) bool

IsRetryable reports whether err says that the peer did not process the stream, so it can be sent again: ErrRejected and ErrGoingAway (retry on this or another session) and ErrEarlyDataRejected (retry on a new session).

func NewHTTPHandler added in v1.3.2

func NewHTTPHandler(l *Listener, o *HTTPOptions) (http.Handler, error)

NewHTTPHandler returns a handler that hands HTTP requests to l as carriers, by their class (ClassifyHTTP): a downlink (the response body), an uplink (the request body) or a bidirectional carrier (both, full duplex). Requests of other classes are served by o.Next. Each carrier first passes l's admission (ListenerConfig.Admission); a request forwarded from early data is answered 425. Nothing is written before a carrier is accepted: with an Admission, the response header goes out when it accepts the request; without one, with the first downlink bytes, and an uplink's once l has taken it. A response that carries a downlink is sent with Cache-Control: no-store and X-Accel-Buffering: no and without a Content-Length, so that intermediaries neither cache nor buffer it. A request that l does not take and to which nothing was written is served by o.Next, with every body byte that l read replayed in front of the rest. The handler returns when the pipe ends. o may be nil; an invalid o is an ErrInvalidConfig error.

func PipeConn added in v1.3.2

func PipeConn(p PipeIO) net.Conn

PipeConn returns p as a net.Conn, for a layer such as tls.Server or tls.Client to run over a carrier (ListenerConfig.WrapPipe, or a Candidate's Dial). On a byte-stream carrier Read and Write go to p's halves as they are; on a message carrier (FramingRecords) each Write is one message and Read returns the bytes of the messages in order. Every Write is exactly one write on p, never merged with another, and a layer over the conn must keep that: one write on p for each write it takes.

Read on a carrier without a receiving half returns io.EOF, and Write without a sending half an error. Close closes both halves, once; CloseWrite ends the sending half where it offers CloseWrite. Addresses and deadlines are those of the halves that have them; a deadline with no half to take it is os.ErrNoDeadline. The conn exposes none of p's other capabilities. The PipeIO of a layer over the conn may set WriteOverhead to the bytes that layer adds to each of its writes.

func PrefixAuthBinding added in v1.3.2

func PrefixAuthBinding(e KeyingMaterialExporter) ([]byte, error)

PrefixAuthBinding returns the binding of a carrier: 32 bytes of its exporter (a *tls.ConnectionState such as CarrierInfo.TLS, or Exporter's result) with PrefixAuthExporterLabel and an empty context.

func PrefixedConn added in v1.3.2

func PrefixedConn(c net.Conn, prefix []byte) net.Conn

PrefixedConn returns c with prefix read before the rest of c. Once the prefix is consumed, WriteTo and ReadFrom use c's own (splice and sendfile where c offers them), and Unwrap returns c.

func PresentPipe added in v1.3.2

func PresentPipe(ctx context.Context, p PipeIO, c Credential) error

PresentPipe writes c's prefix on p, a byte-stream pipe the client opened, before zmux writes on it; a nil c writes nothing. A TLS connection is first handshaken (HandshakeContext, bounded by ctx), so that its state can bind the prefix. A message pipe (FramingRecords) or one without a write half is an ErrInvalidConfig error: a carrier decided on its request head presents c in the request (Header).

func SchemeUpgradeOf added in v1.3.2

func SchemeUpgradeOf(from, to *url.URL) bool

SchemeUpgradeOf reports whether to is from over a secure scheme: the same host, path and query, http to https (or ws to wss).

func StreamConn added in v1.3.0

func StreamConn(s *Stream, local, remote net.Addr) net.Conn

StreamConn returns a net.Conn view of s. Unlike Stream.Close, its Close both finishes the stream and stops reading (CancelRead(StreamNoError)), as net.Conn users expect.

Example

ExampleStreamConn hands a stream to code written for net.Conn.

package main

import (
	"context"
	"fmt"
	"io"
	"net"
	"time"

	"github.com/zmuxio/zmux-go"
)

// sessions returns a client and a server session over an in-memory carrier.
func sessions(ctx context.Context, ccfg, scfg *zmux.Config) (client, server *zmux.Conn, err error) {
	a, b := net.Pipe()
	ch := make(chan error, 1)
	go func() {
		var err error
		server, err = zmux.Server(ctx, b, scfg)
		ch <- err
	}()
	client, err = zmux.Client(ctx, a, ccfg)
	if serr := <-ch; err == nil {
		err = serr
	}
	if err != nil {
		if client != nil {
			_ = client.Close()
		}
		if server != nil {
			_ = server.Close()
		}
		return nil, nil, err
	}
	return client, server, nil
}

// closeBoth closes both sessions and waits for their ends.
func closeBoth(a, b *zmux.Conn) {
	_ = a.Close()
	_ = b.Close()
	_ = a.Wait()
	_ = b.Wait()
}

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	client, server, err := sessions(ctx, nil, nil)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer closeBoth(client, server)
	go func() {
		st, err := server.AcceptStream(ctx)
		if err != nil {
			return
		}
		_, _ = io.Copy(st, st) // echo
		_ = st.Close()
	}()

	st, err := client.OpenStreamSync(ctx)
	if err != nil {
		fmt.Println(err)
		return
	}
	nc := zmux.StreamConn(st, client.LocalAddr(), client.RemoteAddr())
	if _, err := nc.Write([]byte("hello")); err != nil {
		fmt.Println(err)
		return
	}
	buf := make([]byte, 5)
	if _, err := io.ReadFull(nc, buf); err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(string(buf))
	// Close finishes the stream and stops reading, as net.Conn users expect.
	_ = nc.Close()
}
Output:
hello

func TerminatedTLS added in v1.3.3

func TerminatedTLS(p PipeIO) (tls.ConnectionState, bool)

TerminatedTLS reports the state of the TLS (or QUIC) handshake that this process ran for p's carrier (a ConnectionStater half whose handshake completed: a TLS connection, a QUIC stream, a zmuxws WebSocket over TLS terminated here): CarrierInfo.TLS, and a host's test of whether an entrance terminates TLS. It is false for a carrier without TLS, or whose TLS ends at a proxy. It is no proof of an end-to-end handshake: it holds as well when an intermediary reaches this process over TLS of its own; exporters come from Exporter.

func WriteFlat added in v1.3.2

func WriteFlat(w io.Writer, bufs [][]byte) (int, error)

WriteFlat writes bufs to w with one Write of their concatenation, copied into a pooled buffer: one call per batch for a writer whose every call costs a record or a locked hand-over (TLS, a QUIC stream). A BuffersWriter may implement WriteBuffers with it.

Types

type Aborter added in v1.3.3

type Aborter interface{ Abort(cause error) }

Aborter is a sending half that fails abruptly: Abort is used before Close when a pipe fails.

type Admission added in v1.3.2

type Admission struct {
	// Peek is the number of bytes read before Decide (0: none). Decide
	// receives fewer when the carrier ends first. On a message-framed
	// carrier any Peek above 0 reads the first message, of at most
	// max(Peek, MaxPeek) bytes; a longer one is VerdictClose.
	Peek int
	// MaxPeek bounds Decision.Need, the prefix that VerdictMore may ask
	// for, and a first message (0: Peek, so that VerdictMore is
	// VerdictClose). It is not below Peek, or ErrInvalidConfig.
	MaxPeek int
	// PeekTimeout bounds the reading of the prefix, every VerdictMore
	// round included, and the decisions, from the end of the carrier's
	// outer handshake (TLS). Zero selects a
	// value drawn once per Admission, from a secure random source, between
	// 5 s and 30 s; a negative value is no timeout.
	PeekTimeout time.Duration
	// Decide returns the decision for a carrier. prefix is what was read,
	// valid only during the call. ctx ends at what remains of PeekTimeout
	// and when the listener stops taking carriers (Close, or the end of
	// Shutdown); a decision not returned by then is VerdictClose, and so
	// is a panic. It is called once per carrier and once more after each
	// VerdictMore, concurrently for different carriers, outside every
	// lock.
	Decide func(ctx context.Context, info *CarrierInfo, prefix []byte) Decision
	// StallMin and StallMax bound the duration of a VerdictStall. The
	// duration is a function of the carrier's source alone for the
	// Listener's lifetime (Listener.StallDuration). When both are zero,
	// the bounds are drawn once per Admission from a secure random source:
	// StallMax between 30 s and 120 s, StallMin between a quarter and
	// three quarters of it.
	StallMin, StallMax time.Duration
	// contains filtered or unexported fields
}

Admission is a decision taken on a new carrier before any byte is sent on it and before the Listener classifies it. It is configured on the Listener (ListenerConfig.Admission), and every entry point of that listener runs it: Serve, HandlePipe, the HTTP, exchange and upgrade handlers, and the QUIC and WebTransport adapters. The listener reads up to Peek bytes of the carrier (a stream's first bytes after its TLS handshake, an HTTP request's body), never more, and calls Decide with what it read and the carrier's metadata; the Decision says what happens to the carrier. On a message-framed carrier (FramingRecords, such as WebSocket) the prefix is the carrier's first message, whole. Decide may ask for more of a byte stream (VerdictMore, up to MaxPeek bytes), as a host that tells several kinds of carrier apart by their first bytes does (ClassifyFirstBytes).

The fields are read by NewListener; an Admission must not be changed or copied afterwards.

func (*Admission) Validate added in v1.3.2

func (a *Admission) Validate() error

Validate checks a (nil is valid) and resolves its bounds, once; a must not be copied afterwards. NewListener calls it.

type AdmissionStats added in v1.3.2

type AdmissionStats struct {
	Accepted uint64 // VerdictAccept
	// Fallback counts VerdictFallback, also where the carrier has no
	// fallback target.
	Fallback uint64
	Stalled  uint64 // VerdictStall, counted at the decision
	// Closed counts VerdictClose, a decision that panicked, was cancelled,
	// or had a Skip outside the prefix or an unknown verdict.
	Closed uint64
	// StallOverflow counts VerdictStall closed at once: the source held
	// MaxPendingPerSource - 1 stalled carriers.
	StallOverflow uint64
	// PeekTimedOut counts carriers whose prefix or decision did not
	// arrive within PeekTimeout.
	PeekTimedOut uint64
	// HandshakeFailed counts carriers whose outer handshake failed or
	// timed out, without a decision.
	HandshakeFailed uint64
}

AdmissionStats are the outcomes of a listener's admission (API.md 7.2), each carrier that took its source slot and whose outcome is known counted once, so that the sum of the fields is the number of such carriers. All are zero without an Admission.

type ApplicationError

type ApplicationError struct {
	Remote       bool
	ErrorCode    ApplicationErrorCode
	ErrorMessage string
}

ApplicationError is a session closed by an application (CONNECTION_CLOSE 0x1d).

func (*ApplicationError) Error

func (e *ApplicationError) Error() string

Error describes the close.

func (*ApplicationError) Is

func (e *ApplicationError) Is(t error) bool

Is makes every session termination match net.ErrClosed.

type ApplicationErrorCode added in v1.3.0

type ApplicationErrorCode uint64

ApplicationErrorCode is an application error code (62 bits).

type Arrival added in v1.3.2

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

Arrival is a carrier that an entry point of a Listener took: it holds a slot of its source (ListenerConfig.MaxPendingPerSource) from its arrival, before any handshake, through the admission and until the listener classifies the carrier. Listener.Serve, HandlePipe and the HTTP handlers make their own; an adapter with its own accept loop takes one with Arrive (or AdmitUpgrade for an HTTP upgrade) as soon as it accepts a connection, and hands its carriers on with HandlePipe.

func (*Arrival) Admit added in v1.3.2

func (a *Arrival) Admit(ctx context.Context, p PipeIO, fallback func(context.Context, PipeIO)) (PipeIO, bool)

Admit runs the listener's admission on p, the first carrier of the arrival, for an adapter with a fallback target of its own: on VerdictAccept it returns p without the skipped bytes and true, to be handed on with HandlePipe. Otherwise it has acted on the verdict and returns false: VerdictFallback hands p, with every byte read replayed, to fallback (nil: the carrier is stalled), VerdictStall stalls it and VerdictClose closes it. Without an Admission it returns p and true.

func (*Arrival) Admitted added in v1.3.2

func (a *Arrival) Admitted() bool

Admitted reports whether the arrival's carriers are handed on without an admission: the listener has none, or it accepted the arrival.

func (*Arrival) HandlePipe added in v1.3.2

func (a *Arrival) HandlePipe(ctx context.Context, p PipeIO, hint JoinHint) error

HandlePipe hands a carrier of the arrival to the listener and blocks for the lifetime of its pipe, as Listener.HandlePipe does. The first carrier passes the listener's admission (unless AdmitUpgrade decided it already): its outer TLS handshake is completed, its prefix read and the decision taken, and VerdictFallback hands a net.Conn carrier to ListenerConfig.Fallback. Once the arrival is accepted, further carriers of it (a QUIC connection's further streams) are handed on without an admission, each taking a slot of the source. hint.Source is ignored: the arrival's source applies. Hand on the first carrier alone and further ones only once it has been accepted (Admitted): first carriers handed on concurrently are each admitted on their own, with a decision each.

func (*Arrival) HandshakeFailed added in v1.3.2

func (a *Arrival) HandshakeFailed()

HandshakeFailed records that the arrival's outer handshake (an HTTP upgrade, a QUIC handshake) failed or timed out, and releases it: with an Admission it counts as AdmissionStats.HandshakeFailed, otherwise as a setup failure.

func (*Arrival) Release added in v1.3.2

func (a *Arrival) Release()

Release gives back the arrival's source slot when no carrier of it is handed on (the connection ended first). It may be called more than once, also after HandlePipe.

type BuffersWriter added in v1.3.2

type BuffersWriter interface {
	// WriteBuffers writes bufs in order, as one Write of their
	// concatenation would. It may consume bufs (advance or empty its
	// elements) but retains neither bufs nor their contents once it
	// returns.
	WriteBuffers(bufs [][]byte) (int, error)
}

BuffersWriter is an optional capability of a byte-stream sending half that takes a batch of buffers in one call, as net.Buffers does for a net.Conn: one flush or one locked copy per batch instead of one per buffer.

type CacheOutcome added in v1.3.3

type CacheOutcome uint8

CacheOutcome is what a host learnt of a candidate (CarrierCache.Report).

const (
	// CacheUsable means that the candidate worked, as a chosen one does.
	CacheUsable CacheOutcome = iota
	// CacheFailed means an ordinary failure; the backoff doubles.
	CacheFailed
	// CacheRejected means a definite verdict, such as a binding check that
	// proves the path unsuitable; the candidate is skipped for
	// BackoffMax.
	CacheRejected
)

type Candidate added in v1.3.2

type Candidate struct {
	Kind CarrierKind
	Dial func(ctx context.Context, cred Credential) (PipeIO, error)
	// Target, for a kind dialed at a URL, is where its carriers start and
	// what redirects led them to (nil: not known). DialMode keeps it per
	// server in ModePolicy.Cache, and starts it at the base URL again
	// after a failure.
	Target *HTTPTarget
	// Variant labels a transform the candidate's carriers run (PipeIO.Variant,
	// which DialMode sets on what Dial returns when it is not ""). A kind
	// with different variants makes different candidates, each with its
	// own CarrierCache entry; DialMode orders them as for different kinds,
	// so that the host states its preference by their order.
	Variant string
	// contains filtered or unexported fields
}

Candidate is one carrier kind that DialMode may use. Dial opens a carrier of the kind, presenting cred (the session's Config.Credential) for the server's admission; DialMode sets its PipeIO.Carrier to Kind. The carrier must live until the pipe ends, not until ctx does, which bounds only the opening. The constructors of each adapter return ready candidates.

func ExchangeCandidate added in v1.3.2

func ExchangeCandidate(client *http.Client, url string, cfg *HTTPExchangeConfig) Candidate

ExchangeCandidate is an exchange carrier (HTTPExchangePipe) to url with client and cfg. It passes intermediaries that buffer whole bodies; it authenticates with cfg's PSK, and the session's credential is not presented on it.

func SplitCandidate added in v1.3.2

func SplitCandidate(client *http.Client, url string, h http.Header) Candidate

SplitCandidate is a split bootstrap (HTTPSplitPipe) to url with client and the fields h. As a further pipe of a session it joins as an uplink POST and a downlink GET joined out of band, two pipes. Its carriers must be confidential end to end or up to a trusted TLS-terminating intermediary.

func StreamingCandidate added in v1.3.2

func StreamingCandidate(client *http.Client, url string, h http.Header) Candidate

StreamingCandidate is a bidirectional streaming request (HTTPPipe) to url with client and the fields h. It passes intermediaries that forward both bodies at once: HTTP/2 or HTTP/3 to the server, or HTTP/1.1 hops that do not buffer request bodies.

type CandidateOutcome added in v1.3.2

type CandidateOutcome uint8

CandidateOutcome is the outcome of one try of a candidate.

const (
	// CandidateUsable means the peer's transport parameters (for a join, the
	// join's confirmation) arrived within the timer.
	CandidateUsable CandidateOutcome = iota + 1
	// CandidateTimedOut means the carrier was opened but the timer expired; it
	// was closed without CONNECTION_CLOSE.
	CandidateTimedOut
	// CandidateRefused means the server or an intermediary refused the carrier,
	// such as with an HTTP status other than 2xx or a refused connection.
	CandidateRefused
	// CandidateFailed means any other failure.
	CandidateFailed
)

func (CandidateOutcome) String added in v1.3.2

func (o CandidateOutcome) String() string

String returns "usable", "timed_out", "refused" or "failed".

type CandidateResult added in v1.3.2

type CandidateResult struct {
	Variant string // the candidate's Variant
	// Err is the failure (nil when usable).
	Err     error
	Kind    CarrierKind
	Outcome CandidateOutcome
	// Joined is set for a try as a further pipe of the established session.
	Joined bool
}

CandidateResult is the outcome of one try of a candidate.

type CapacityFloor added in v1.3.0

type CapacityFloor struct {
	Rate      float64
	RateRatio float64
}

CapacityFloor asks for EventCapacityBelow once the summed delivery rate of the usable, non-standby outbound pipes falls below Rate (bytes per second, as every delivery rate of the API), and EventCapacityRestored once it is back at Rate*RateRatio. A zero Rate turns it off, so the zero CapacityFloor reports nothing; a zero RateRatio means 1.25.

type CarrierCache added in v1.3.2

type CarrierCache struct {
	// SuccessTTL is how long a usable kind is remembered (6 h).
	SuccessTTL time.Duration
	// BackoffMin and BackoffMax bound the backoff of a failed kind (1 min,
	// 6 h).
	BackoffMin, BackoffMax time.Duration
	// contains filtered or unexported fields
}

CarrierCache remembers which carrier kinds worked per server and local network (ModePolicy.Key): a usable kind for SuccessTTL, a failed one is skipped for a backoff that doubles with every failure in a row, from BackoffMin to BackoffMax. A kind that fails soon after it was chosen (ModePolicy.DropWindow) counts as failed, so that a path that lets a kind through only briefly is not tried again at once. The zero value is ready; the fields must not change once it is in use. It is safe for concurrent use.

func (*CarrierCache) Report added in v1.3.3

func (cc *CarrierCache) Report(key string, kind CarrierKind, variant string, o CacheOutcome)

Report records an outcome the host learnt after DialMode for the candidate of kind and variant under key (the ModePolicy.Key in use), in the entry DialMode's own outcomes use. Safe for concurrent use.

func (*CarrierCache) Restore added in v1.3.2

func (cc *CarrierCache) Restore(data []byte) error

Restore merges a Snapshot into the cache. For a key and kind the cache already holds, or that the snapshot holds more than once, the newer entry (the later of its two times is later) is kept. A nonzero backoff outside BackoffMin and BackoffMax is brought within them, a good time further ahead than SuccessTTL or a fail time further ahead than BackoffMax is brought back to that bound, and expired entries are dropped. Unknown fields, and entries of a kind this version does not know, are ignored. A version other than 1, a field of the wrong type, a negative backoff or malformed JSON is an error wrapping ErrInvalidConfig that leaves the cache as it was.

func (*CarrierCache) Snapshot added in v1.3.2

func (cc *CarrierCache) Snapshot() ([]byte, error)

Snapshot returns what the cache knows, to be restored by Restore, such as in the next run of the process: JSON of the form

{"version": 1, "entries": [{"key": "...", "kind": "streaming",
  "good_until": "2026-11-01T12:00:00Z", "fail_until": "...",
  "backoff_ms": 60000, "url": "..."}]}

with the kinds by name (CarrierKind.String) and the times on the wall clock. An entry is expired, and left out, when both its times and its fail time plus BackoffMax have passed.

type CarrierConner added in v1.3.3

type CarrierConner interface{ CarrierConn() any }

CarrierConner is a half that names the carrier connection it runs on (comparable), so that the pipes of one connection share lane keys and fate.

type CarrierInfo added in v1.3.2

type CarrierInfo struct {
	// Source is the carrier's client address: what a trusted intermediary
	// reports (TrustedProxies; port 0 when it reports none), what the
	// host gave as JoinHint.Source, and otherwise Peer. The listener's
	// per-source limits and the stall duration count it aggregated: an
	// IPv6 address to its /64 prefix, the port ignored.
	Source netip.AddrPort
	// Peer is the address the carrier arrived from: the remote address of
	// its connection, or an HTTP request's RemoteAddr. Zero when it is not
	// an IP address and port, such as a Unix socket.
	Peer netip.AddrPort
	// TLS is the state of the carrier's TLS (or QUIC) handshake, which has
	// completed; ExportKeyingMaterial binds data to it. For a carrier
	// decided on an HTTP request head it is the state of the connection
	// that carries the request. It is nil where TLS ended at an
	// intermediary.
	TLS *tls.ConnectionState
	// Request is the request of an HTTP carrier. Its body must not be read
	// by Decide; the bytes the listener read are the prefix.
	Request *http.Request
	// Head marks a carrier decided on its HTTP request head, before any
	// body byte is read: an HTTP upgrade such as WebSocket or
	// WebTransport, an exchange carrier, or an HTTP request carrier
	// without a body, such as a downlink GET. There is no prefix, and a
	// credential travels in a request header field.
	Head bool
}

CarrierInfo is the metadata of a carrier under admission, or of one a client opens (Credential). Fields that do not apply to the carrier are zero.

type CarrierKind added in v1.3.2

type CarrierKind uint8

CarrierKind names a kind of carrier.

const (
	// CarrierWebSocket is a WebSocket (zmuxws.Candidate).
	CarrierWebSocket CarrierKind = iota + 1
	// CarrierStreaming is a bidirectional streaming request: one request
	// whose body is the uplink and whose response body the downlink
	// (StreamingCandidate).
	CarrierStreaming
	// CarrierSplit is a split bootstrap: an uplink POST and a downlink GET
	// (SplitCandidate).
	CarrierSplit
	// CarrierExchange is the exchange carrier of bounded requests
	// (ExchangeCandidate).
	CarrierExchange
	// CarrierQUIC is a QUIC stream (zmuxquic.Candidate), direct only.
	CarrierQUIC
	// CarrierHTTP3 is a streaming request over HTTP/3
	// (zmuxh3.HTTP3Candidate).
	CarrierHTTP3
	// CarrierWebTransport is a WebTransport stream
	// (zmuxh3.WebTransportCandidate), direct only.
	CarrierWebTransport
)

func (CarrierKind) String added in v1.3.2

func (k CarrierKind) String() string

String returns the kind's name: "websocket", "streaming", "split", "exchange", "quic", "http3" or "webtransport".

type CarrierPool added in v1.3.0

type CarrierPool[C comparable] struct {
	// Dial opens an underlying connection.
	Dial func(ctx context.Context) (C, error)
	// Close closes a connection the pool retired once no pipe uses it.
	Close func(C)
	// PoolLimits bound the use of each connection; set them before the
	// first Get.
	PoolLimits
	// contains filtered or unexported fields
}

CarrierPool shares underlying connections between pipes, for adapters that carry several pipes over one connection (HTTP/2 and HTTP/3 request streams, QUIC streams). A new pipe goes to the open connection with the most room within the limits, else to a new one; a connection that reached its lifetime limits takes no new pipe and is closed once its last pipe ends. The pipes of one connection get one fate group: they fail together and are never counted as independent paths. The zero value with Dial set is ready; it is safe for concurrent use.

func (*CarrierPool[C]) Get added in v1.3.0

func (p *CarrierPool[C]) Get(ctx context.Context) (*Lease[C], error)

Get returns a lease on a connection with room, dialling one when none has; the dial runs outside the pool's lock. The lease is non-nil exactly when the error is nil.

func (*CarrierPool[C]) RetireConn added in v1.3.0

func (p *CarrierPool[C]) RetireConn(c C)

RetireConn retires connection c (for example when it failed): it takes no new pipe and closes once its pipes are released.

func (*CarrierPool[C]) Shutdown added in v1.3.0

func (p *CarrierPool[C]) Shutdown()

Shutdown retires every connection: idle ones close now, the others when their last pipe ends; Get fails afterwards.

type ChannelDemux added in v1.3.2

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

ChannelDemux routes the channel datagrams of one carrier connection shared by several pipes, such as a QUIC connection or a WebTransport session, to those pipes by their Pipe Stream ID (EXTENSIONS.md 6.8). An adapter runs one receive loop per connection that passes every datagram to Deliver, and its pipes' ReceiveChannelDatagrams register with Register. The pipes may belong to several sessions. The zero value is ready to use.

func (*ChannelDemux) Deliver added in v1.3.2

func (d *ChannelDemux) Deliver(b []byte)

Deliver routes one channel datagram to the pipe its Pipe Stream ID names; one that names no registered pipe (unknown, not yet attached, or closed) or whose ID is truncated is dropped and counted.

func (*ChannelDemux) Dropped added in v1.3.2

func (d *ChannelDemux) Dropped() uint64

Dropped returns the datagrams Deliver dropped because they named no registered pipe.

func (*ChannelDemux) Register added in v1.3.2

func (d *ChannelDemux) Register(id uint64, deliver func(frame []byte)) (stop func())

Register hands the datagrams for Pipe Stream ID id to deliver until stop is called; a later Register of the same ID replaces it.

type Chunk added in v1.3.0

type Chunk struct {
	Data []byte
	// contains filtered or unexported fields
}

Chunk is stream data passed on without a copy. A chunk read with ReadChunk references the session's receive buffer until it is released: by WriteChunk, which takes ownership in every outcome, or by Release. Its Data must not be changed, and must not be used after Release.

Copies on the way out: ReadFrom reads into the pooled send blocks and WriteChunk queues the chunk's memory, so neither copies in user space; what the carrier does when the session sends those blocks is its own: a TCP connection takes them with writev, no copy; *tls.Conn flattens once while encrypting; a QUIC stream flattens once; an HTTP request body is copied once by the Transport and an HTTP response body once by its bufio writer; WebSocket flattens once per record; a stream of an outer session (nested sessions) takes them without a copy.

func (*Chunk) Release added in v1.3.0

func (c *Chunk) Release()

Release returns the chunk's buffer; the chunk must not be used after.

type CloseWriter added in v1.3.3

type CloseWriter interface{ CloseWrite() error }

CloseWriter is a sending half with a graceful end of its write side, used instead of Close when the session ends its sending.

type Config

type Config struct {
	// HandshakeTimeout bounds establishment and join confirmation. Zero
	// is 10 s; a negative value is no timeout.
	HandshakeTimeout time.Duration
	// MaxIdleTimeout is max_idle_timeout, the time without inbound
	// activity after which the session closes. Zero is 30 s; a negative
	// value announces no idle timeout; a positive one is at least 1 ms.
	MaxIdleTimeout time.Duration
	// KeepAlivePeriod sends a QX_PING when the session has had no activity
	// this long. Zero is 15 s; a negative value turns keep-alive off, as
	// for net.Dialer.KeepAlive; a positive one is at least 1 s. The period in effect is capped at half the
	// effective idle timeout, and each wait is drawn from [k x (1 - j), k]
	// with j the probe jitter (SchedulerParams.ProbeJitter). On, an idle
	// session stays open while the peer answers and closes within the
	// idle timeout once its carrier dies; off, the idle timeout ends any
	// session without application activity.
	KeepAlivePeriod time.Duration

	// InitialStreamReceiveWindow is the initial receive window of a
	// stream. Zero is 256 KiB; otherwise at least 4 KiB.
	InitialStreamReceiveWindow uint64
	// MaxStreamReceiveWindow caps the auto-tuning of a stream's window.
	// Zero is automatic: a 64 MiB floor that grows within the memory
	// budget.
	MaxStreamReceiveWindow uint64
	// LatencyBudget is the B of window auto-tuning. Zero is 100 us (tuning
	// needs a positive budget); a negative value is invalid.
	LatencyBudget time.Duration
	// InitialConnectionReceiveWindow is the initial session window. Zero
	// is 1 MiB; otherwise at least 16 KiB.
	InitialConnectionReceiveWindow uint64
	// MaxConnectionReceiveWindow caps the session window. Zero is
	// automatic: a 96 MiB floor.
	MaxConnectionReceiveWindow uint64
	// MemoryBudget bounds the memory of a session without a listener.
	// Zero is 1 GiB; NoMemoryLimit is unlimited; another negative value
	// is invalid.
	MemoryBudget int64

	// MaxIncomingStreams is initial_max_streams_bidi, the bidirectional
	// streams the peer may open at first. Zero is 256; otherwise at least
	// 4; granting none takes NoIncomingStreams; a negative value is
	// invalid.
	MaxIncomingStreams int64
	// NoIncomingStreams grants the peer no bidirectional stream.
	NoIncomingStreams bool
	// MaxIncomingUniStreams is initial_max_streams_uni. Zero is a staged
	// credit: 16, raised to 256 on the first AcceptUniStream; a negative
	// value is invalid.
	MaxIncomingUniStreams int64
	// NoIncomingUniStreams grants the peer no unidirectional stream.
	NoIncomingUniStreams bool

	// EnableDatagrams announces max_datagram_frame_size and datagram flows.
	EnableDatagrams bool
	// DatagramSendQueue, DatagramReceiveQueue, DatagramStreamQueue (per
	// stream) and DatagramReceiveBytes size the datagram queues. Zero is
	// 64, 128, 32 and 1 MiB (an empty queue would drop every datagram); a
	// negative value is invalid.
	DatagramSendQueue    int
	DatagramReceiveQueue int
	DatagramStreamQueue  int
	DatagramReceiveBytes int

	// SendBuffer starts the written-but-unreleased byte budget. Zero is
	// 4 MiB. Multipath sessions grow it to the retransmit budget, within
	// MaxSendBuffer.
	SendBuffer uint64
	// MaxSendBuffer fixes its growth maximum (at least SendBuffer). Zero is
	// automatic: a 64 MiB floor, above it within the memory budget.
	MaxSendBuffer uint64

	// MaxPipes is the attachments this endpoint aims for. Zero or 1 is
	// multipath off; 8 is recommended when multipath is used.
	MaxPipes int
	// PipeHeadroom is H of the attachment cap. Zero is 8.
	PipeHeadroom int
	// ReplayWindow is W. Zero is max(64, 2*(MaxPipes+H)); a smaller
	// window is raised to MaxPipes+H.
	ReplayWindow int
	// MaxLanes is the lanes accepted per inbound pipe. Zero is 258; 1
	// accepts the stream lane only.
	MaxLanes int

	// ResumeTimeout enables resume with this grace period. Zero is no
	// resume.
	ResumeTimeout time.Duration

	// Scheduler is the session's scheduling policy (nil: Affinity).
	Scheduler Scheduler
	// SchedulerParams tune the scheduler and failure detection.
	SchedulerParams SchedulerParams
	// ShapingLimits bound what a Shaper adds (SetShaper); a negative
	// duration or a MaxPaddingRatio outside [0, 1] is invalid.
	ShapingLimits shaping.Limits
	// Shaper is installed when the session is created, as by SetShaper
	// (nil: no shaping): every outbound pipe of the session, the
	// bootstrap pipe of an accepted session and joined pipes included, is
	// shaped from its first record. SetShaper replaces it.
	Shaper ShaperFactory

	// PipeAuth selects the join secret (required for multipath).
	PipeAuth PipeAuth

	// EarlyData enables early data (SPEC.md 6.1.2).
	EarlyData EarlyData

	// DatagramLimiter polices datagrams in each direction:
	// a datagram passes when TryReady allows its whole payload, and is
	// then charged; otherwise it is dropped and counted.
	DatagramLimiter DatagramLimiter

	// Tracer receives session events on a goroutine of its own.
	Tracer *Tracer
	// Credential is presented on the carrier of a client session by the
	// functions that open one with this Config: Client, Dial and DialTLS
	// and the dialers of zmuxquic, zmuxws and zmuxh3 (nil: none). Pipes
	// opened otherwise, for AddPipe or Redial, present theirs where they
	// are dialed (PresentPipe, the adapters' options).
	Credential Credential
	// Redial re-establishes pipes after failures (resume): it is called
	// as soon as the session lacks a direction or suspends, delayed only
	// by the wait since its previous call for that direction. It keeps
	// one pipe per direction; a session that keeps several pipes is
	// maintained with Conn.MaintainPipes and a PipePool, which also
	// replaces failed pipes, and leaves Redial nil.
	Redial func(ctx context.Context, need Direction) (PipeIO, error)
	// RedialPolicy, when set, is asked before each Redial call; DialAfter
	// is the wait from the previous call to the next (at most 30 s; 0: the
	// built-in backoff), and ProbeInterval and ProbeJitter apply to the
	// pipe a call yields. Count and Retire are not used. A decision that
	// fails PoolDecision.Validate is rejected: the call goes ahead as with
	// the zero decision and the error is reported to DecisionRejected.
	RedialPolicy PoolPolicy
	// DecisionRejected, when set, receives the PoolDecision.Validate error
	// (ErrInvalidConfig) of each decision of RedialPolicy the session
	// rejected, on the goroutine that calls Redial and outside every lock;
	// it must not block, and a panic in it is contained. Redialling goes
	// on whether it is set or not.
	DecisionRejected func(err error)
	// AllowConnectionWindowIncrease approves session window growth.
	AllowConnectionWindowIncrease func(delta uint64) bool
	// Clock is the session's time source (nil: the host's monotonic
	// clock): every session timer (handshake, idle, keep-alive, probes,
	// resume grace, retransmission, shaping and pacing), the RTT and rate
	// estimates, stream deadlines and the Redial and PipePool waits run on
	// it, so a fake clock drives them deterministically. What stays on
	// the host clock is listed in the package documentation (Time).
	Clock timeshim.Clock
}

Config configures a session; nil *Config means all defaults. Its fields follow the Settings rules of the package documentation: the zero value selects the stated default, a negative timeout is no timeout, other negative values are invalid (ErrInvalidConfig) unless the field gives them a meaning, and the Disable and No fields switch features off.

func (*Config) Clone added in v1.3.0

func (c *Config) Clone() *Config

Clone returns a shallow copy (nil means defaults): slices such as PipeAuth.PSK and EarlyData.Remembered and the function fields are shared.

type Conn

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

Conn is a zmux session. Its methods are safe for concurrent use.

Concurrency model: one mutex guards the sans-IO core; no I/O, blocking or application code runs under it. Each pipe direction has a reader and a writer goroutine; wake-ups are queued under the lock and delivered after it is released.

func Client

func Client(ctx context.Context, c net.Conn, cfg *Config) (*Conn, error)

Client starts a client session on a connection the caller established (TCP, TLS, Unix or any net.Conn), like tls.Client; it returns as Start does. With cfg.Credential, the connection starts with its prefix (PresentPipe; a *tls.Conn is handshaken first). The session owns c from then on, unless Client fails with ErrInvalidConfig.

func Dial added in v1.3.0

func Dial(ctx context.Context, network, addr string, cfg *Config) (*Conn, error)

Dial connects to addr on the named network (as net.Dialer.DialContext) and starts a client session on the connection, which the session owns from then on. It returns as Start does; ctx bounds the dial and the handshake.

func DialMode added in v1.3.2

func DialMode(ctx context.Context, m Mode, cfg *Config, pol *ModePolicy) (*Conn, error)

DialMode dials a client session over the carrier the mode selects. ctx bounds the dial and the handshakes; each carrier presents cfg.Credential. pol is the policy of AutoMode (nil: the defaults).

ExplicitMode dials its one candidate as its own dialer does. AutoMode does not use early data (cfg.EarlyData is ignored), so that nothing the application sends goes out before a carrier is chosen, and it does not race candidates: it skips the kinds the cache holds as failed (unless all are) and, when cfg.MaxPipes is above 1, establishes the session on the most robust candidate (a kind the cache holds as usable, else the exchange carrier, else the last) and joins the preferred ones as further pipes in the background, retiring the pipes of the kind they replace once one has stayed joined for ModePolicy.Settle; it keeps retrying preferred kinds as their backoff expires, and joins the best kind available again when the active one fails. Without joins (MaxPipes 1, NoJoin, or a peer without multipath) it tries the candidates one after another, in order, and keeps the first usable one.

Each try of a candidate is reported as an EventCarrierCandidate, the choice as an EventCarrierChosen (again on every switch), and both in ConnectionStats. When no candidate is usable, the error is a *ModeError.

func DialTLS added in v1.3.0

func DialTLS(ctx context.Context, network, addr string, tlsConf *tls.Config, cfg *Config) (*Conn, error)

DialTLS connects to addr on the named network, runs the TLS handshake with tlsConf (as tls.Dialer.DialContext) and starts a client session on the TLS connection, which the session owns from then on. ctx bounds the dial and both handshakes.

Example

ExampleDialTLS serves zmux over TLS (tls.NewListener) and dials it with DialTLS.

package main

import (
	"context"
	"crypto/ecdsa"
	"crypto/elliptic"
	"crypto/rand"
	"crypto/tls"
	"crypto/x509"
	"fmt"
	"io"
	"math/big"
	"net"
	"time"

	"github.com/zmuxio/zmux-go"
)

// echo answers every stream of conn with what it read, until conn ends.
func echo(ctx context.Context, conn *zmux.Conn) {
	for {
		st, err := conn.AcceptStream(ctx)
		if err != nil {
			return
		}
		go func() {
			_, _ = io.Copy(st, st)
			_ = st.Close()
		}()
	}
}

// roundTrip opens a stream, sends msg, finishes the stream and returns the
// answer.
func roundTrip(ctx context.Context, conn *zmux.Conn, msg string) (string, error) {
	st, err := conn.OpenStreamSync(ctx)
	if err != nil {
		return "", err
	}
	if _, err := st.Write([]byte(msg)); err != nil {
		return "", err
	}
	if err := st.Close(); err != nil {
		return "", err
	}
	b, err := io.ReadAll(st)
	return string(b), err
}

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	serverTLS, clientTLS, err := testTLSConfigs()
	if err != nil {
		fmt.Println(err)
		return
	}

	ln, err := net.Listen("tcp", "127.0.0.1:0")
	if err != nil {
		fmt.Println(err)
		return
	}
	l := zmux.NewListener(nil)
	go func() { _ = l.Serve(ctx, tls.NewListener(ln, serverTLS)) }()
	go func() {
		for {
			conn, err := l.Accept(ctx)
			if err != nil {
				return
			}
			go echo(ctx, conn)
		}
	}()

	conn, err := zmux.DialTLS(ctx, "tcp", ln.Addr().String(), clientTLS, nil)
	if err != nil {
		fmt.Println(err)
		return
	}
	reply, err := roundTrip(ctx, conn, "hello over TLS")
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(reply)
	_ = conn.Shutdown(ctx, 0, "")
	_ = l.Shutdown(ctx, 0, "")
}

// testTLSConfigs returns TLS configurations with a fresh self-signed
// certificate for 127.0.0.1.
func testTLSConfigs() (server, client *tls.Config, err error) {
	key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		return nil, nil, err
	}
	tmpl := &x509.Certificate{
		SerialNumber: big.NewInt(1),
		NotBefore:    time.Now().Add(-time.Hour),
		NotAfter:     time.Now().Add(time.Hour),
		IPAddresses:  []net.IP{net.IPv4(127, 0, 0, 1)},
		KeyUsage:     x509.KeyUsageDigitalSignature,
		ExtKeyUsage:  []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
	}
	der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key)
	if err != nil {
		return nil, nil, err
	}
	cert, err := x509.ParseCertificate(der)
	if err != nil {
		return nil, nil, err
	}
	pool := x509.NewCertPool()
	pool.AddCert(cert)
	server = &tls.Config{Certificates: []tls.Certificate{{Certificate: [][]byte{der}, PrivateKey: key}},
		MinVersion: tls.VersionTLS13}
	client = &tls.Config{RootCAs: pool, MinVersion: tls.VersionTLS13}
	return server, client, nil
}
Output:
hello over TLS

func Server

func Server(ctx context.Context, c net.Conn, cfg *Config) (*Conn, error)

Server starts a single-pipe server session on an accepted connection, like tls.Server. For multipath, resume or pipe joins use a Listener (Listener.Serve accepts sessions and joins on a net.Listener): Server rejects Config.MaxPipes above 1 with ErrInvalidConfig. The session owns c from then on, unless Server fails with ErrInvalidConfig.

func Start added in v1.3.0

func Start(ctx context.Context, p PipeIO, role Role, cfg *Config) (*Conn, error)

Start establishes a session over any carrier with an explicit role. It returns once the peer's transport parameters were processed, or at once when the session may send early data (EarlyData.ZmuxPeer, or EarlyData.Replayable with Remembered parameters); ConnectionState's Established is false until the parameters arrive.

func (*Conn) AcceptStream

func (c *Conn) AcceptStream(ctx context.Context) (*Stream, error)

AcceptStream returns the next bidirectional stream the peer opened.

func (*Conn) AcceptUniStream

func (c *Conn) AcceptUniStream(ctx context.Context) (*ReceiveStream, error)

AcceptUniStream returns the next unidirectional stream the peer opened. The first call grants the staged unidirectional credit.

func (*Conn) AddPipe added in v1.3.0

func (c *Conn) AddPipe(ctx context.Context, p PipeIO, o PipeOptions) (*Pipe, error)

AddPipe joins a new carrier to the session in band (MULTIPATH.md 5.7) and waits until the join is confirmed, the pipe fails, or ctx ends (the pipe is then removed). A join that the attachment cap or the refusal backoff holds waits for room. With CarrierBound, a carrier whose TLS handshake (a *tls.Conn half, or a Handshaker) has not completed is first driven through it with ctx; a failed handshake closes it and is returned.

Example

ExampleConn_AddPipe joins a second pipe to a session and follows its state with NextEvent. Multipath needs MaxPipes above 1 and a join secret on both sides, and a Listener on the server.

ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
cfg := &zmux.Config{MaxPipes: 2, PipeAuth: zmux.PipeAuth{PSK: []byte("an example pre-shared key, 32 B")}}
l := zmux.NewListener(&zmux.ListenerConfig{Config: cfg})
defer func() { _ = l.Close() }()

// Two carriers between the same endpoints (two paths in practice).
a0, b0 := net.Pipe()
a1, b1 := net.Pipe()
go func() { _ = l.HandlePipe(ctx, zmux.NetPipe(b0), zmux.JoinHint{}) }()
go func() { _ = l.HandlePipe(ctx, zmux.NetPipe(b1), zmux.JoinHint{}) }()

client, err := zmux.Client(ctx, a0, cfg)
if err != nil {
	fmt.Println(err)
	return
}
server, err := l.Accept(ctx)
if err != nil {
	fmt.Println(err)
	return
}
defer closeBoth(client, server)

p, err := client.AddPipe(ctx, zmux.NetPipe(a1), zmux.PipeOptions{Label: "backup", SendStandby: new(true)})
if err != nil {
	fmt.Println(err)
	return
}
for {
	ev, err := client.NextEvent(ctx)
	if err != nil {
		fmt.Println(err)
		return
	}
	if ev.Kind == zmux.EventPipeJoined && ev.Pipe == p.ID() {
		break
	}
}
st, ok := p.Stats()
if !ok {
	fmt.Println(zmux.ErrPipeGone)
	return
}
fmt.Println(len(client.Pipes()), "pipes;", st.Label, st.Outbound, "standby:", st.Standby)
Output:
2 pipes; backup active standby: true

func (*Conn) Admitted added in v1.3.2

func (c *Conn) Admitted() any

Admitted returns the Decision.Value of the admission that accepted the session's bootstrap carrier (for a split bootstrap, its uplink half's), nil without one and on the dialing side. It does not change for the session's lifetime, resumes included; Pipe.Admitted is each pipe's.

func (*Conn) Close

func (c *Conn) Close() error

Close closes the session at once with application error code 0, discarding data not yet sent; it never blocks. Unlike net.Conn.Close it does not flush: to let the peer read what was written, call Shutdown(ctx, 0, "") instead. Wait waits for the end.

func (*Conn) CloseWithError added in v1.0.4

func (c *Conn) CloseWithError(code ApplicationErrorCode, msg string) error

CloseWithError closes the session immediately with an application error; it never blocks. Unsent data is discarded.

func (*Conn) ConnectionState added in v1.3.0

func (c *Conn) ConnectionState() ConnectionState

ConnectionState returns the negotiation results.

func (*Conn) ConnectionStats added in v1.3.0

func (c *Conn) ConnectionStats() ConnectionStats

ConnectionStats returns a snapshot of the session's statistics.

func (*Conn) Context added in v1.3.0

func (c *Conn) Context() context.Context

Context is canceled when the session ends; context.Cause returns its error.

func (*Conn) DesignateDialer added in v1.3.0

func (c *Conn) DesignateDialer(e Endpoint)

DesignateDialer records which endpoint dialed a session whose bootstrap carrier is symmetric (role auto), for ResolveDuplicate. A value other than EndpointLocal or EndpointPeer forgets the designation.

func (*Conn) ExportKeyingMaterial added in v1.3.3

func (c *Conn) ExportKeyingMaterial(label string, ctxData []byte, length int) ([]byte, error)

ExportKeyingMaterial exports keying material (RFC 5705, RFC 8446 Section 7.5) from the innermost end-to-end handshake of the bootstrap carrier, the source Exporter finds (the carrier's own exporter, a transform's, or the TLS handshake this process runs). For a split bootstrap whose halves are two connections the result is the uplink's value followed by the downlink's, 2*length bytes, as for PipeAuth.Exporter. It fails with ErrNoExporter when the carrier has none, ErrInvalidConfig for a label of zmux's own ("EXPORTER-zmux-"), which keys the joins, and with the carrier's error while its handshake is incomplete. Both ends obtain the same value.

func (*Conn) JoinReady added in v1.3.0

func (c *Conn) JoinReady() bool

JoinReady reports whether the maintenance target and join admission permit dialing another pipe now. Explicit AddPipe still follows the physical cap.

func (*Conn) Liveness added in v1.3.3

func (c *Conn) Liveness() Liveness

Liveness returns the session's liveness settings in effect, resolved: defaults are filled in, a setting that is off is negative (a jitter of 0 is NoProbeJitter), and a derived DeadTimeout is zero, so that SetLiveness with the result changes nothing.

func (*Conn) LocalAddr added in v1.3.0

func (c *Conn) LocalAddr() net.Addr

LocalAddr returns the local address of pipe 0 when its carrier has one.

func (*Conn) MaintainPipes added in v1.3.0

func (c *Conn) MaintainPipes(ctx context.Context, pool PipePool) error

MaintainPipes keeps pool.Count usable pipes dialled by pool.Dial: it redials failed pipes with exponential backoff and rotates pipes by pool.Rotate, until ctx ends or the session closes. The backoff, or the policy's DialAfter in its place, counts from the start of the previous dial attempt (a rotation's included), or from the start of the pool before the first. The pool decides again at once on pipe failures, the loss of a direction and the suspension of the session, keeps dialling while the session is suspended, and dials outside every lock. It returns ctx's error or the session's; when ctx ends, a replacement still being rotated in is closed and the pool's other pipes stay.

func (*Conn) NextEvent added in v1.3.0

func (c *Conn) NextEvent(ctx context.Context) (Event, error)

NextEvent returns the next session event, waiting until one arrives, ctx ends or the session ends. Once the session has ended and no event is left it returns the session's error.

Events wait in a queue of the session bounded at 1024 events. Reading it is optional: when nobody calls NextEvent the oldest events are dropped, so a reader that falls behind sees the latest events and can read the current state with PipeStats. The queue is independent of Config.Tracer: a Tracer receives every event as well, on its own bounded queue, whether or not NextEvent is called. Concurrent callers each receive different events.

func (*Conn) OpenPipeStream added in v1.3.0

func (c *Conn) OpenPipeStream(ctx context.Context, tlvs ...TLV) (PipeIO, error)

OpenPipeStream opens a stream of c to carry a pipe pair of another session; tlvs are application TLVs of its preamble (for example routing metadata for relays), to which PIPE_CARRIER is added. Nothing is sent before the nested session writes its first record.

func (*Conn) OpenStream

func (c *Conn) OpenStream() (*Stream, error)

OpenStream opens a bidirectional stream without waiting; without stream credit it returns StreamLimitReachedError. Nothing is sent before the first write (or StreamID).

func (*Conn) OpenStreamSync added in v1.3.0

func (c *Conn) OpenStreamSync(ctx context.Context) (*Stream, error)

OpenStreamSync opens a bidirectional stream, waiting for credit in FIFO order.

func (*Conn) OpenUniStream

func (c *Conn) OpenUniStream() (*SendStream, error)

OpenUniStream opens a unidirectional stream without waiting.

func (*Conn) OpenUniStreamSync added in v1.3.0

func (c *Conn) OpenUniStreamSync(ctx context.Context) (*SendStream, error)

OpenUniStreamSync opens a unidirectional stream, waiting for credit.

func (*Conn) Ping

func (c *Conn) Ping(ctx context.Context) (time.Duration, error)

Ping sends a QX_PING request (or joins the outstanding one) and returns the measured round-trip time.

func (*Conn) Pipe added in v1.3.0

func (c *Conn) Pipe(id uint64) (*Pipe, bool)

Pipe returns the handle of attachment id while the session knows it.

func (*Conn) PipeStats added in v1.3.0

func (c *Conn) PipeStats() []PipeStats

PipeStats returns a snapshot of every attachment. A session without multipath reports pipe 0.

func (*Conn) Pipes added in v1.3.0

func (c *Conn) Pipes() []*Pipe

Pipes returns the handles of the session's current attachments. A session without multipath has pipe 0.

func (*Conn) RaiseIncomingStreams added in v1.3.3

func (c *Conn) RaiseIncomingStreams(bidi, uni int64) error

RaiseIncomingStreams raises the number of bidirectional and of unidirectional streams the peer may have open (MaxIncomingStreams, MaxIncomingUniStreams) to bidi and uni while the session runs, and sends the credit as MAX_STREAMS. The credit only grows (SPEC.md 8.5): a value at or below the current one leaves that type as it is, so 0 raises nothing. While the unidirectional credit is still staged (MaxIncomingUniStreams zero), uni raises the value the first AcceptUniStream moves it to. After GOAWAY no credit is sent. A negative value or one above 2^60 is an ErrInvalidConfig error that changes nothing.

func (*Conn) ReceiveDatagram added in v1.3.0

func (c *Conn) ReceiveDatagram(ctx context.Context) ([]byte, error)

ReceiveDatagram returns the next session datagram.

func (*Conn) ReleaseFirstFlight added in v1.3.3

func (c *Conn) ReleaseFirstFlight()

ReleaseFirstFlight ends EarlyData.HoldFirstFlight: everything queued so far is built into records and written to the bootstrap carrier in one write (one Write or WriteBuffers on a byte stream, one WriteMessages where the half is a MessageBatchWriter), as far as one batch holds it. Calls after the first, and on a session without HoldFirstFlight, do nothing. It never blocks.

func (*Conn) RememberedParameters added in v1.3.0

func (c *Conn) RememberedParameters() []byte

RememberedParameters returns the peer's transport parameters for a later session's carrier early data (EarlyData.Remembered); store them only with the application's consent, per peer.

func (*Conn) RemoteAddr added in v1.3.0

func (c *Conn) RemoteAddr() net.Addr

RemoteAddr returns the remote address of pipe 0 when its carrier has one.

func (*Conn) ReservePipe added in v1.3.0

func (c *Conn) ReservePipe(dir Direction, o PipeOptions) (*Reservation, error)

ReservePipe reserves a pipe for an out-of-band join.

func (*Conn) RevalidatePipes added in v1.3.0

func (c *Conn) RevalidatePipes() error

RevalidatePipes revalidates every live outbound pipe (after a network change).

func (*Conn) SendDatagram added in v1.3.0

func (c *Conn) SendDatagram(p []byte) error

SendDatagram queues a session datagram; it never blocks: a full queue drops its oldest datagram. p is copied.

Example

ExampleConn_SendDatagram sends an unreliable datagram; both endpoints enable datagrams.

ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
cfg := &zmux.Config{EnableDatagrams: true}
client, server, err := sessions(ctx, cfg, cfg)
if err != nil {
	fmt.Println(err)
	return
}
defer closeBoth(client, server)

// SendDatagram never blocks and drops the oldest queued datagram when
// the queue is full; SendDatagramWait waits for room instead.
if err := client.SendDatagramWait(ctx, []byte("ping")); err != nil {
	fmt.Println(err)
	return
}
d, err := server.ReceiveDatagram(ctx)
if err != nil {
	fmt.Println(err)
	return
}
fmt.Printf("%s\n", d)
Output:
ping

func (*Conn) SendDatagramWait added in v1.3.0

func (c *Conn) SendDatagramWait(ctx context.Context, p []byte) error

SendDatagramWait queues a session datagram, waiting for room in the send queue instead of dropping its oldest entry.

func (*Conn) SessionBinding added in v1.3.3

func (c *Conn) SessionBinding() []byte

SessionBinding returns a 32-byte value that identifies this session, the same at both ends: HKDF-Extract (SHA-256) of the two Session Nonces under a fixed label (MULTIPATH.md Section 10.3). An application includes it in an authentication transcript to bind that authentication to this session. It is public, not a secret. It is nil before establishment and when multipath is not in use, whose parameter carries the nonces (ConnectionState().Multipath).

func (*Conn) SetCapacityFloor added in v1.3.0

func (c *Conn) SetCapacityFloor(f CapacityFloor)

SetCapacityFloor sets the capacity floor of the outbound direction.

func (*Conn) SetJoinSecret added in v1.3.3

func (c *Conn) SetJoinSecret(psk []byte) error

SetJoinSecret supplies the PSK of PipeAuth.DeferredPSK, at least 16 bytes, once: the join keys are derived from it (with the exporter when both are selected, MULTIPATH.md 10.3) and the held joins of the peer go on. Called before establishment, the PSK is kept for the negotiation: when that does not select the PSK (the peer offered no P), it is dropped, and ConnectionState().JoinSecretPending stays false. It fails with ErrInvalidConfig without DeferredPSK or with a shorter PSK, ErrNotNegotiated after an establishment that did not select the PSK (also when one was supplied before), ErrJoinSecretSet when already supplied, and with the session's error once it is closed.

func (*Conn) SetLiveness added in v1.3.3

func (c *Conn) SetLiveness(l Liveness) error

SetLiveness replaces the session's liveness settings as a whole, under the rules of Config: zero fields are the defaults, not the values the session was started with, and an invalid l is an ErrInvalidConfig error that changes nothing. The timers are rearmed at once: the keep-alive period (still capped at half the effective idle timeout), the probe intervals and the suspicion floor apply to the waits in progress, a jitter from the next draw, and the DeadTimeout to pipes that turn suspect from then on; a pipe already suspect keeps the SuspectFloor and DeadTimeout it turned suspect under. A pipe's own settings (PipeOptions, Pipe.SetLiveness) keep winning; every other pipe, and those joined later, follow the new values. Nothing is sent.

func (*Conn) SetPipeShaper added in v1.3.2

func (c *Conn) SetPipeShaper(pipe uint64, s shaping.Shaper) bool

SetPipeShaper installs s on one outbound pipe until the next SetShaper; nil: the pipe is not shaped. It reports whether the pipe exists.

func (*Conn) SetQualityBand added in v1.3.0

func (c *Conn) SetQualityBand(b QualityBand) error

SetQualityBand sets the default band of the session's pipes.

func (*Conn) SetScheduler added in v1.3.0

func (c *Conn) SetScheduler(s Scheduler)

SetScheduler changes the session's scheduling policy; it applies from the next chunk.

func (*Conn) SetShaper added in v1.3.2

func (c *Conn) SetShaper(f ShaperFactory)

SetShaper installs f on every outbound pipe of the session, replacing earlier instances; nil: no shaping.

A deadline that a Shaper sets (a delay, a gate) is met precisely: the session's timer is armed ahead of it by the host timer's observed lateness, at most 2 ms, and its callback then yields in a loop until the deadline. Each shaping deadline so costs up to that lead in CPU time on one goroutine; a Shaper that sets deadlines at a high rate trades CPU for timing precision.

func (*Conn) SetShapingLimits added in v1.3.3

func (c *Conn) SetShapingLimits(l shaping.Limits) error

SetShapingLimits replaces the session's Config.ShapingLimits: records planned from then on follow l, whether shaping is installed yet or not. Limits may be tightened or loosened (they bound this endpoint's own overhead and are never sent). Padding and pause already spent stay counted: past a tightened bound nothing more is padded or paused, and nothing already sent is undone. An invalid l fails with ErrInvalidConfig and changes nothing.

func (*Conn) ShapingLimits added in v1.3.3

func (c *Conn) ShapingLimits() shaping.Limits

ShapingLimits returns the session's shaping limits.

func (*Conn) ShapingStats added in v1.3.2

func (c *Conn) ShapingStats() shaping.Stats

ShapingStats returns the shaping counters.

func (*Conn) Shutdown added in v1.3.0

func (c *Conn) Shutdown(ctx context.Context, code ApplicationErrorCode, msg string) error

Shutdown closes gracefully: it sends GOAWAY when the session negotiated it, so that the peer opens no new stream, waits until the open streams have ended, then closes with code and msg. When ctx ends first it falls back to CloseWithError(code, msg) and returns ctx's error. The usual call is

ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
err := conn.Shutdown(ctx, 0, "")
Example

ExampleConn_Shutdown ends a session gracefully: the stream the server is still reading is delivered in full before the session closes, which Close would not wait for.

ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
client, server, err := sessions(ctx, nil, nil)
if err != nil {
	fmt.Println(err)
	return
}
defer closeBoth(client, server)

got := make(chan int, 1)
go func() {
	st, err := server.AcceptStream(ctx)
	if err != nil {
		got <- -1
		return
	}
	b, _ := io.ReadAll(st)
	_ = st.Close()
	got <- len(b)
}()

st, err := client.OpenStreamSync(ctx)
if err != nil {
	fmt.Println(err)
	return
}
if _, err := st.Write(make([]byte, 1<<20)); err != nil {
	fmt.Println(err)
	return
}
_ = st.Close()
go func() { _, _ = io.Copy(io.Discard, st) }()

if err := client.Shutdown(ctx, 0, "done"); err != nil {
	fmt.Println(err)
	return
}
fmt.Println("server read", <-got, "bytes")
Output:
server read 1048576 bytes

func (*Conn) Wait

func (c *Conn) Wait() error

Wait blocks until the session is closed and every goroutine of it has ended, then returns the session's error.

type ConnectionState added in v1.3.0

type ConnectionState struct {
	Role               Role
	Established        bool
	SupportsDatagrams  struct{ Local, Remote bool }
	SupportsResetAt    struct{ Local, Remote bool }
	Multipath          bool
	PipeAck            bool
	Resume             bool
	JoinSecurityAbsent bool
	// JoinSecretPending: the negotiation selected PipeAuth.DeferredPSK and
	// Conn.SetJoinSecret has not supplied it yet; no join is possible.
	JoinSecretPending bool
	PeerIsZmux        bool
	// PeerGoAway holds the watermarks of the GOAWAY frames received (the
	// minimum per stream type) and the latest error code; nil while none
	// was received. EventGoAwayReceived reports each one.
	PeerGoAway         *GoAway
	MaxDatagramPayload int
}

ConnectionState reports the negotiation results.

type ConnectionStater added in v1.3.3

type ConnectionStater interface {
	ConnectionState() tls.ConnectionState
}

ConnectionStater is a half whose TLS (or QUIC) handshake this process runs: the state behind TerminatedTLS and CarrierInfo.TLS. A state without HandshakeComplete counts as no TLS.

type ConnectionStats added in v1.3.0

type ConnectionStats struct {
	// Carrier is the carrier kind a carrier mode chose (DialMode), the
	// latest after a switch; 0 for a session not dialed in a mode.
	// CarrierVariant is that candidate's Variant.
	Carrier        CarrierKind
	CarrierVariant string
	// CarrierCandidates are the tries of the mode's candidates in order,
	// joins of preferred kinds included: the latest 64.
	CarrierCandidates []CandidateResult

	// BytesSent and BytesReceived count every byte of the records passed
	// to and received from the carriers (framing, frames of every kind,
	// copies and acknowledgements included), not what a carrier adds.
	BytesSent, BytesReceived     uint64
	RecordsSent, RecordsReceived uint64

	// The application bytes (API.md 7.1): stream payload the application
	// wrote and read, and datagram payload handed to a carrier and
	// returned to the application.
	BytesWritten, BytesRead                  uint64
	DatagramBytesSent, DatagramBytesReceived uint64

	// StreamsOpenedLocal counts a local stream when its first frame is
	// emitted or it is pinned, StreamsOpenedRemote a peer stream when it is
	// first seen.
	StreamsOpenedLocal, StreamsOpenedRemote uint64
	StreamsActive                           uint64 // gauge: streams the session holds
	StreamCreditWaits                       uint64 // opens that waited for stream-count credit

	// DatagramsSent counts session and stream datagrams handed to a
	// carrier, DatagramsReceived those received and queued for the
	// application; the Channel counts are those of them on a carrier
	// datagram channel (DatagramChannel).
	DatagramsSent, DatagramsReceived               uint64
	DatagramsSentChannel, DatagramsReceivedChannel uint64
	// DatagramsDroppedSend counts datagrams dropped from the send queue,
	// DatagramsDroppedRecv received ones dropped (a full queue, an unknown
	// or closed stream, the byte limit), DatagramsDroppedLimit those a
	// datagram limiter dropped, either way.
	DatagramsDroppedSend, DatagramsDroppedRecv, DatagramsDroppedLimit uint64

	NoEffectBudget uint64 // gauge: tokens of the no-effect budget

	// The RTT of pipe 0 outside multipath, of the primary pipe in a
	// multipath session; MeanDeviation is 0 where the source measures no
	// variation.
	SmoothedRTT, MinRTT, LatestRTT, MeanDeviation time.Duration

	// BytesReinjected counts stream bytes sent again after a pipe failed
	// or became suspect, or opportunistically; BytesOpportunistic those
	// of them sent opportunistically.
	BytesReinjected, BytesOpportunistic uint64
	Penalties                           uint64 // pipes penalized for slowing down
	Reinjections                        uint64 // reinjection episodes
	BytesRedundant                      uint64 // stream bytes sent as redundant copies
	BytesDuplicateReceived              uint64 // stream bytes received again (multipath)

	SendBuffered uint64 // gauge: written stream bytes not yet sent
	RecvBuffered uint64 // gauge: received stream bytes not yet read
	Retained     uint64 // gauge: sent stream bytes not yet acknowledged (multipath)

	PipesActive      uint64 // gauge: ACTIVE outbound pipes
	PipesAdded       uint64 // attachments, the bootstrap pair included
	PipeFailures     uint64
	JoinAuthFailures uint64 // joins whose token did not verify
	JoinReplays      uint64 // joins closed as replays or too late
	// JoinSecretPending counts peer joins held for PipeAuth.DeferredPSK
	// (not join auth failures).
	JoinSecretPending uint64
	JoinRefusals      uint64 // own joins refused with ZMUX_PIPE_RESOURCE_LIMIT, or answered with ZMUX_RESUME_FAILED
	Suspensions       uint64
	SuspendedTime     time.Duration // the current suspension included

	SchedulerAnswers   uint64 // custom scheduler answers that named a pipe and were applied; Wait is not counted
	SchedulerFallbacks uint64 // answers replaced by the affinity choice
	// FirstFlightTimeouts is 1 when EarlyData.HoldFirstFlight was released
	// by Config.HandshakeTimeout rather than ReleaseFirstFlight.
	FirstFlightTimeouts uint64
}

ConnectionStats is a snapshot of a session's statistics (API.md 7.2). Each field holds a value it had during the call; relations between counts (a subset, a sum) hold for their final values, not in every snapshot. Counts only increase, from 0 when the session was made; the fields marked gauge are current values. A duration or RTT that is absent (before the first sample) is 0.

type Credential added in v1.3.2

type Credential interface {
	// Prefix returns the bytes a carrier starts with, before any zmux
	// record: byte streams, HTTP request bodies, a QUIC connection's
	// first stream.
	Prefix(info *CarrierInfo) ([]byte, error)
	// Header returns the request header field of a carrier decided on its
	// HTTP request head (WebSocket, WebTransport, a request without a
	// body); info.TLS is the state of the connection that carries the
	// request.
	Header(info *CarrierInfo) (name, value string, err error)
}

Credential is what a client presents on a carrier it opens, for the server's Admission: the client side of an Admission. info describes the carrier as CarrierInfo does on the server: Remote is the server's address and TLS the carrier's completed handshake (nil without TLS); Head is set for Header. PrefixAuth is a Credential.

The adapters present it: zmux.Client, Dial and DialTLS take Config.Credential, as the QUIC, WebSocket and WebTransport dialers of the sub-modules do; HTTPPipe and HTTPSplitPipe take one; PresentPipe presents it on any other byte-stream pipe. Methods are called concurrently.

type DatagramChannel added in v1.3.2

type DatagramChannel interface {
	// ChannelStreamID returns the Pipe Stream ID that starts the pipe's
	// channel datagrams: the carrier stream ID of the pipe on channels
	// shared by the streams of a connection (QUIC, WebTransport); ok is
	// false on a channel of the pipe's own stream (HTTP/3).
	ChannelStreamID() (id uint64, ok bool)
	// MaxChannelDatagram returns the largest channel datagram, Pipe Stream
	// ID included, that the channel takes now; 0 while it takes none (the
	// carrier did not negotiate datagrams, or has not yet). It must be
	// cheap and must not block: it is called under the session's lock.
	MaxChannelDatagram() int
	// SendChannelDatagram sends one channel datagram. It may block while
	// the carrier's own queue is full: a goroutine of the pipe calls it,
	// and the session's datagram queue drops its oldest datagrams
	// meanwhile. It retains nothing of b once it returns.
	SendChannelDatagram(b []byte) error
	// ReceiveChannelDatagrams starts handing the channel datagrams received
	// for the pipe, Pipe Stream ID removed, to deliver, one call at a time,
	// until stop is called. deliver takes the argument over: the channel
	// does not reuse its bytes. It does not wait for the session's lock.
	// It is called under the session's lock, when the pipe attaches and
	// before its first record, so it must not block.
	ReceiveChannelDatagrams(deliver func(frame []byte)) (stop func())
}

DatagramChannel is the datagram channel of a pipe's carrier, an optional capability of a PipeIO half (EXTENSIONS.md 6.8): an unreliable datagram service of the carrier besides the reliable stream that is the pipe, such as QUIC DATAGRAM frames of the connection a QUIC stream belongs to, the HTTP Datagrams of an HTTP/3 request stream, or the datagrams of a WebTransport session. When both endpoints negotiate it, a session sends a DATAGRAM frame that fits the channel on it instead of in a record, so that a lost carrier packet loses that datagram instead of delaying every later one; nothing changes for the application. A session uses the channel only when it enables datagrams.

type DatagramLimiter added in v1.3.0

type DatagramLimiter struct {
	Send, Receive Limiter
}

DatagramLimiter holds the limiters of the two datagram directions.

type DatagramTooLargeError added in v1.3.0

type DatagramTooLargeError struct{ MaxDatagramPayloadSize int64 }

DatagramTooLargeError reports the largest payload the peer accepts.

func (*DatagramTooLargeError) Error added in v1.3.0

func (e *DatagramTooLargeError) Error() string

Error describes the limit.

type Decision added in v1.3.2

type Decision struct {
	Verdict Verdict
	// Skip is the number of leading prefix bytes that are not carrier bytes
	// (VerdictAccept only); the rest is replayed to the Listener.
	Skip int
	// Value is the host's value for an accepted carrier (VerdictAccept
	// only; ignored otherwise): zmux hands it on without looking at it to
	// WrapPipe (JoinHint.Admitted) and to the session (Conn.Admitted) or
	// pipe (Pipe.Admitted) the carrier makes, and holds it until their
	// state is released. Whether a join comes from the same client as its
	// session is the host's to decide: zmux compares no values.
	Value any
	// Need is, with VerdictMore, the total prefix length Decide needs.
	Need int
	// Variant labels the carrier with any verdict, for
	// Listener.VariantStats; on VerdictAccept it is the PipeIO.Variant
	// handed to WrapPipe (which may change it). "" for none. Use one of a
	// few constants of the host, never a value derived from the peer's
	// bytes: at most MaxAdmissionVariants are counted apart.
	Variant string
}

Decision is what Admission.Decide returns.

type Direction

type Direction uint8

Direction is a pipe direction from the local endpoint's view.

const (
	DirBidirectional Direction = iota
	DirSendOnly
	DirReceiveOnly
)

type DuplicateOptions added in v1.3.0

type DuplicateOptions struct {
	// LocalID and PeerID are the application identities of the two
	// endpoints (the same byte strings at both ends), when it has them.
	LocalID, PeerID []byte
	// Rejoin: when this endpoint dialed the losing session and the
	// survivor uses multipath, Dial the route again and join it to the
	// survivor (in the background; a hint).
	Rejoin bool
	Dial   func(ctx context.Context) (PipeIO, error)
}

DuplicateOptions are the inputs of ResolveDuplicate.

type DuplicateResult added in v1.3.0

type DuplicateResult struct {
	Survivor, Loser *Conn
	RejoinStarted   bool
}

DuplicateResult reports a resolution.

func ResolveDuplicate added in v1.3.0

func ResolveDuplicate(s1, s2 *Conn, opts *DuplicateOptions) (DuplicateResult, error)

ResolveDuplicate applies the rule of EXTENSIONS.md 11 to two established sessions that connect the same two endpoints and were dialed by different endpoints: it returns the survivor and starts draining the other session (GOAWAY, no new streams, close with NO_ERROR once its streams have ended). It changes nothing when the sessions have the same dialer or no input decides.

type EarlyClientCarrier added in v1.3.0

type EarlyClientCarrier interface {
	// SendsEarlyData reports whether this pipe's initial bytes go out as
	// carrier early data, which the server may refuse or see replayed; it
	// must not change for the pipe. A carrier that sends them only after
	// its handshake (QUIC without 0-RTT) returns false: floor early data
	// (EarlyData.ZmuxPeer) then neither waits for a verdict nor needs
	// Replayable. Remembered parameters with Replayable wait for
	// EarlyAccepted either way.
	SendsEarlyData() bool
	// EarlyAccepted waits for the carrier handshake's verdict for this pipe's
	// initial bytes. Return true if they remain usable, including bytes sent
	// only after the handshake. Return false only when those bytes were
	// invalidated and RestartEarly must supply their replacement stream.
	EarlyAccepted(ctx context.Context) (bool, error)
	// RestartEarly returns the pipe as it stands after the handshake: new
	// halves, with their Framing, WriteOverhead and capabilities (on QUIC
	// the bootstrap stream opened again; the bootstrap halves are closed),
	// or the bootstrap halves themselves, with the same Framing (a layered
	// carrier past its handshake, which discarded what it held; the
	// session goes on with them). Halves of both kinds fail the session.
	// The session sets Carrier, Label, FateGroup and Variant from the
	// bootstrap pipe.
	RestartEarly(ctx context.Context) (PipeIO, error)
}

EarlyClientCarrier is the optional capability of a client carrier that may send early data, on the W half of the bootstrap PipeIO. When SendsEarlyData reports true, the session's early sends stay provisional until EarlyAccepted returns.

type EarlyData added in v1.3.0

type EarlyData struct {
	// Remembered are the peer's parameters from an earlier session, as
	// Conn.RememberedParameters returned them (client only). Store them per
	// server and only with the application's consent.
	Remembered []byte
	// ZmuxPeer declares the peer a zmux endpoint (client only).
	ZmuxPeer bool
	// Replayable allows carrier early data, which the peer may see
	// replayed (TLS 1.3, QUIC 0-RTT, a transform's first flight): on a
	// client with Remembered, or with ZmuxPeer on a carrier with early
	// data; on a server to accept it and mark its streams.
	Replayable bool
	// HoldFirstFlight keeps the bootstrap pipe's first carrier write until
	// Conn.ReleaseFirstFlight, or until Config.HandshakeTimeout has passed
	// since Start (ConnectionStats.FirstFlightTimeouts); the handshake
	// timeout runs from the release. Streams opened and written before the
	// release leave in the same write as the transport parameters, as a
	// carrier whose first message carries the first flight wants. Client
	// with early data only (ZmuxPeer, or Remembered with Replayable);
	// otherwise ErrInvalidConfig.
	HoldFirstFlight bool
}

EarlyData lets a client send stream data before the server's transport parameters arrive (SPEC.md 6.1.2). With either form, Start, Client and Dial return at once and ConnectionState().Established stays false until the parameters arrive.

ZmuxPeer: the client knows the server is a zmux endpoint and writes its first streams on the bootstrap carrier right away, within the floor values every zmux endpoint grants. Nothing is replayable, unless the carrier itself sends early data (its W half is an EarlyClientCarrier whose SendsEarlyData is true, such as a transform whose first message carries the first flight; not QUIC without 0-RTT): the streams then travel in it, wait for its verdict and are sent again after a rejection, as with Remembered below, and the client consents to replay with Replayable (else Start fails with ErrInvalidConfig).

Replayable with Remembered: the client sends its first streams in the carrier's own early data (QUIC 0-RTT through zmuxquic.Dial), under the parameters remembered from an earlier session with the same server (Conn.RememberedParameters). When the carrier refuses its early data, the session sends those streams again after the handshake, without telling the application. Carrier early data can be replayed by an attacker, so the server sets Replayable as well: its streams that arrived in early data then report Stream.Replayable, and a server that must not act on a replayed request calls Stream.Reject on it; the client gets a *StreamError for which IsRetryable is true, and opens the stream again on the same session.

When the server cannot take the early data at all (it is not a zmux endpoint, or it grants no bidirectional stream), it processes none of it and the session ends with *EarlyDataRejectedError: every call on the session and its streams that is waiting or comes later (Read, Write, AcceptStream, Wait, ...) returns it. errors.Is(err, ErrEarlyDataRejected) and IsRetryable report it; retry on a new session without EarlyData, since the cause persists. Remembered parameters above what the server grants now end the session with a *TransportError (TransportParameterError) instead: forget them.

Example

ExampleEarlyData sends a request before the server's parameters arrive, and retries it without early data when the server rejects it. This server grants no stream before its parameters arrive, so it cannot take early data; a real client meets this when its peer is not a zmux endpoint.

ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

// First attempt: the request is sent before the server even runs.
a, b := net.Pipe()
ga := newHeldConn(a)
cfg := &zmux.Config{EarlyData: zmux.EarlyData{ZmuxPeer: true}}
client, err := zmux.Client(ctx, ga, cfg) // returns at once
if err != nil {
	fmt.Println(err)
	return
}
st, err := client.OpenStreamSync(ctx)
if err != nil {
	fmt.Println(err)
	return
}
_, _ = st.Write([]byte("request"))
_ = st.Close()
_ = st.SetReadDeadline(time.Now().Add(5 * time.Second))
ga.releaseAfter(ctx, []byte("request")) // the server starts only now
go func() {
	server, err := zmux.Server(ctx, b, &zmux.Config{NoIncomingStreams: true})
	if err == nil {
		_ = server.Wait()
	}
}()
reply, err := io.ReadAll(st)
_ = client.Wait()

if errors.Is(err, zmux.ErrEarlyDataRejected) && zmux.IsRetryable(err) {
	// Nothing was processed: send the request again on a new session
	// without early data.
	fmt.Println("early data rejected; retrying without it")
	client, server, err := sessions(ctx, nil, nil)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer closeBoth(client, server)
	go echo(ctx, server)
	var s string
	s, err = roundTrip(ctx, client, "request")
	reply = []byte(s)
	if err != nil {
		fmt.Println(err)
		return
	}
} else if err != nil {
	fmt.Println(err)
	return
}
fmt.Printf("%s\n", reply)
Output:
early data rejected; retrying without it
request

type EarlyDataRejectedError added in v1.3.0

type EarlyDataRejectedError struct{}

EarlyDataRejectedError reports that the peer could not take early data and processed none of it: retry on a new session (see EarlyData). It matches ErrEarlyDataRejected and net.ErrClosed, and IsRetryable reports true for it.

func (*EarlyDataRejectedError) Error added in v1.3.0

func (e *EarlyDataRejectedError) Error() string

Error describes the rejection.

func (*EarlyDataRejectedError) Is added in v1.3.0

Is matches ErrEarlyDataRejected and net.ErrClosed.

type EarlyServerCarrier added in v1.3.0

type EarlyServerCarrier interface {
	UsedEarlyData() bool
	HandshakeComplete() <-chan struct{}
}

EarlyServerCarrier is the optional capability of a server carrier that accepted early data, on the W half: with EarlyData.Replayable, streams opened before HandshakeComplete is closed report Stream.Replayable.

type Endpoint added in v1.3.2

type Endpoint uint8

Endpoint names one end of a session, seen from this end.

const (
	EndpointLocal Endpoint = iota + 1
	EndpointPeer
)

func (Endpoint) String added in v1.3.2

func (e Endpoint) String() string

type Event

type Event struct {
	Kind EventKind
	// Direction of a pipe event, from the local endpoint.
	Direction Direction
	// Standby (EventPipePriorityChanged) and Saturated
	// (EventTierSaturation).
	Standby   bool
	Saturated bool
	// Reason of EventJoinAuthFailed.
	Reason JoinAuthReason
	// Carrier is the pipe's carrier kind (PipeIO.Carrier) of a pipe event,
	// the candidate's of EventCarrierCandidate and EventCarrierChosen;
	// Outcome that of EventCarrierCandidate.
	Carrier CarrierKind
	Outcome CandidateOutcome
	// Variant is the PipeIO.Variant of a pipe event's carrier while the
	// pipe has one, and the candidate's of EventCarrierCandidate and
	// EventCarrierChosen.
	Variant string
	// Pipe is the pipe ID of a pipe event.
	Pipe uint64
	// Priority is the tier (EventPipePriorityChanged,
	// EventTierSaturation); Weight the pipe's weight
	// (EventPipePriorityChanged).
	Priority uint64
	Weight   uint64
	// GoAway of EventGoAwayReceived.
	GoAway *GoAway
	// SmoothedRTT and DeliveryRate (bytes per second) of
	// EventPipeQualityChanged;
	// DeliveryRate is also the capacity of EventCapacityBelow and
	// EventCapacityRestored.
	SmoothedRTT  time.Duration
	DeliveryRate float64
	// Retired counts the pipes retired since EventPipesRetired was last
	// read; Failed and Closed, of those, the ones whose failure or end
	// without failure had not been read; Dropped the non-terminal events
	// the queue's bound dropped meanwhile; Last the IDs of the last
	// retired pipes, at most four, oldest first. An application that
	// needs every retired ID compares Pipes with the handles it holds.
	Retired, Failed, Closed, Dropped uint64
	Last                             []uint64
}

Event is a session event, as NextEvent and Tracer.Event report it. Kind says which of the other fields are set (see EventKind).

type EventKind added in v1.3.0

type EventKind uint8

EventKind is the kind of a session event. The comment of each kind names the Event fields it sets; the other fields are zero.

const (
	// EventPipeAdded reports that a local outbound pipe direction appeared
	// (Pipe, Direction).
	EventPipeAdded EventKind = iota + 1
	// EventPipeJoined reports that an outbound pipe direction became active
	// (Pipe, Direction).
	EventPipeJoined
	// EventPipeSuspect reports that an outbound pipe direction stopped making
	// progress (Pipe, Direction).
	EventPipeSuspect
	// EventPipeRecovered reports that a suspect outbound direction is active
	// again (Pipe, Direction).
	EventPipeRecovered
	// EventPipeFailed reports that an outbound pipe direction failed (Pipe,
	// Direction).
	EventPipeFailed
	// EventPipeClosed reports that a pipe direction ended: the outbound
	// one closed (DirSendOnly) or the inbound one ended (DirReceiveOnly)
	// (Pipe, Direction). Retirement is reported by EventPipesRetired.
	EventPipeClosed
	// EventPipePriorityChanged reports that the effective tier, standby state
	// or weight of an outbound pipe changed (Pipe, Priority, Standby, Weight).
	EventPipePriorityChanged
	// EventTierSaturation reports that the usable pipes of a tier became
	// saturated or stopped being so (Priority, Saturated).
	EventTierSaturation
	// EventJoinAuthFailed reports that a join failed authentication
	// (Reason).
	EventJoinAuthFailed
	// EventSessionSuspended reports that every pipe of a direction was lost and
	// the session waits for a resume (no fields).
	EventSessionSuspended
	// EventSessionResumed reports that a suspended session has a pipe again (no
	// fields).
	EventSessionResumed
	// EventGoAwayReceived reports that the peer sent GOAWAY (GoAway).
	EventGoAwayReceived
	// EventJoinSecurityUnavailable reports that both endpoints offered
	// multipath but no join secret is available, so no pipe can join (no
	// fields).
	EventJoinSecurityUnavailable
	// EventPipeQualityChanged reports that an outbound pipe left its
	// QualityBand (Pipe, SmoothedRTT, DeliveryRate).
	EventPipeQualityChanged
	// EventCapacityBelow reports that the outbound capacity fell below the
	// CapacityFloor (DeliveryRate: the capacity).
	EventCapacityBelow
	// EventCapacityRestored reports that the outbound capacity is back above
	// the CapacityFloor (DeliveryRate: the capacity).
	EventCapacityRestored
	// EventCarrierCandidate reports a try of a candidate of DialMode
	// (Carrier, Outcome).
	EventCarrierCandidate
	// EventCarrierChosen reports the carrier kind DialMode chose, and every
	// later switch to another kind (Carrier).
	EventCarrierChosen
	// EventPipesRetired is the one report of retirement (Retired, Failed,
	// Closed, Dropped, Last): it enters the queue at the first retirement
	// after the previous one was read and accumulates until it is read, the
	// unread events of each retired pipe leaving the queue for it.
	EventPipesRetired
)

func (EventKind) String added in v1.3.0

func (k EventKind) String() string

type FirstBytes added in v1.3.3

type FirstBytes uint8

FirstBytes is what the first bytes of a carrier tell of its content (ClassifyFirstBytes).

const (
	// FirstBytesNeedMore means that more bytes are needed to tell.
	FirstBytesNeedMore FirstBytes = iota
	// FirstBytesRecord means that the bytes can begin a first record of
	// this specification.
	FirstBytesRecord
	// FirstBytesOther means that the bytes cannot begin a first record.
	FirstBytesOther
)

func ClassifyFirstBytes added in v1.3.3

func ClassifyFirstBytes(b []byte, f Framing) (c FirstBytes, need int)

ClassifyFirstBytes tells whether b, the first bytes a carrier delivered with framing f (for FramingRecords, the start of the first message), can begin a first record of this specification: on a byte stream a Size of at least 9 and at most MaxRecordSize, as a variable-length integer of 1, 2 or 4 bytes, then a first frame type (SPEC.md 6.2; its encoding begins with ff, 9a or ba, REGISTRY.md 2.4); in a message, the first frame type at once. need is the total number of bytes needed (at most MaxFirstBytes) when the result is FirstBytesNeedMore, else 0.

It judges the syntax of a prefix only, not the limits of a receiver (the full check of SPEC.md 6.2 is the session's). b beginning 16 03, as TLS does, is always FirstBytesOther. It is the one authority for hosts and transforms that tell zmux records from other content, at admission (Admission.Decide) or when drawing a prefix that must not look like one (redrawn until both framings give FirstBytesOther).

func (FirstBytes) String added in v1.3.3

func (c FirstBytes) String() string

type Framing added in v1.3.0

type Framing uint8

Framing is a carrier's record framing (SPEC.md 3.1, 3.4).

const (
	// FramingByteStream concatenates records with their Size fields.
	FramingByteStream Framing = iota
	// FramingRecords carries one message per record, without Size (as on
	// WebSocket); the halves implement MessageReader and MessageWriter.
	FramingRecords
)

type GoAway added in v1.3.0

type GoAway struct {
	MaxBidi, MaxUni uint64
	// ErrorCode is the GOAWAY's application error code.
	ErrorCode ApplicationErrorCode
}

GoAway are the watermarks of a received GOAWAY (EXTENSIONS.md Section 3): streams the receiver initiated with an index at or above MaxBidi (bidirectional) or MaxUni (unidirectional) were not and will not be processed by the peer, and fail with a retryable error.

type HTTPClass added in v1.3.2

type HTTPClass uint8

HTTPClass is the carrier class of an HTTP request on a unified endpoint, decided by its head alone.

const (
	// HTTPClassNone is a request that is not a carrier: the host's.
	HTTPClassNone HTTPClass = iota
	// HTTPClassWebSocket is a WebSocket opening handshake: a GET with
	// Upgrade: websocket, or an extended CONNECT for websocket.
	HTTPClassWebSocket
	// HTTPClassWebTransport is an extended CONNECT for webtransport (or
	// a versioned token such as webtransport-h3).
	HTTPClassWebTransport
	// HTTPClassDownlink is a GET with Zmux-Pipe-Pair or Zmux-Pipe-Join.
	HTTPClassDownlink
	// HTTPClassUplink is a POST with Zmux-Pipe-Pair (a split bootstrap's
	// uplink), or one without a Content-Length that carries
	// Zmux-Pipe-Join.
	HTTPClassUplink
	// HTTPClassExchange is a POST with a Content-Length, an exchange carrier.
	HTTPClassExchange
	// HTTPClassBidirectional is a POST without a Content-Length.
	HTTPClassBidirectional
)

func ClassifyHTTP added in v1.3.2

func ClassifyHTTP(r *http.Request) HTTPClass

ClassifyHTTP classifies a request by its head alone, before any body byte is read, by the first of its rules that matches. It is the one classification of every HTTP adapter: NewHTTPHandler serves the downlink, uplink and bidirectional classes and HTTPEndpoint dispatches all of them.

func (HTTPClass) String added in v1.3.2

func (c HTTPClass) String() string

type HTTPDatagramChannel added in v1.3.2

type HTTPDatagramChannel interface {
	// DatagramChannel returns the request stream's datagram channel. The
	// handler calls it once, after the response header was written, while
	// no other write to the response runs.
	DatagramChannel() DatagramChannel
}

HTTPDatagramChannel is an optional capability of an http.ResponseWriter, found through Unwrap: the datagram channel of the request's stream, for HTTP versions that have one, such as HTTP/3 with HTTP Datagrams (RFC 9297; zmuxh3 provides it). The handler of NewHTTPHandler uses it for bidirectional carriers (EXTENSIONS.md 6.8).

type HTTPEndpoint added in v1.3.2

type HTTPEndpoint struct {
	// Stream serves downlinks, uplinks and bidirectional carriers: the
	// handler of NewHTTPHandler.
	Stream http.Handler
	// Exchange serves exchange requests: an *HTTPExchangeHandler.
	Exchange http.Handler
	// WebSocket serves WebSocket opening handshakes, such as
	// zmuxws.Handler.
	WebSocket http.Handler
	// WebTransport serves WebTransport sessions, such as zmuxh3.Handler.
	WebTransport http.Handler
	// Next is the host's handler (nil: http.NotFound). It is served as
	// HTTPOptions.Fallback serves: an HTTP/1.1 request with a body arrives
	// full duplex.
	Next http.Handler
}

HTTPEndpoint serves every HTTP carrier kind on one request target (API.md 4.8): it classifies each request with ClassifyHTTP and hands it to the adapter of its class, which runs its own admission and serves what it does not accept with its own fallback. It adds no behaviour of its own: a request of a class without an adapter, and every request that is not a carrier, goes to Next. Give each adapter the same host handler as its HTTPOptions.Next (HTTPExchangeConfig.Next) so that every request that is not taken reaches the host, with the body bytes the adapter read replayed.

Behind a reverse proxy that speaks HTTP/2 to the server without TLS, serve the endpoint with prior-knowledge HTTP/2 enabled, so that bidirectional carriers pass:

srv := &http.Server{Handler: endpoint, Protocols: new(http.Protocols)}
srv.Protocols.SetHTTP1(true)
srv.Protocols.SetUnencryptedHTTP2(true)

func (*HTTPEndpoint) ServeHTTP added in v1.3.2

func (e *HTTPEndpoint) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP dispatches r by its class.

type HTTPExchangeConfig added in v1.3.2

type HTTPExchangeConfig struct {
	// PSK is the pre-shared key: the MACs authenticate both ends with it.
	PSK []byte
	// AllowInsecure runs the carrier without a PSK, for tests and
	// protected networks: the MACs then only bind responses to requests
	// (they are computed with the empty key), and the carrier ID inside
	// every body is a bearer secret. It must not be combined with PSK.
	AllowInsecure bool
	// Base64 sends every body base64-encoded (standard alphabet, padded),
	// for paths that do not pass binary bodies unchanged.
	Base64 bool

	// NoCacheBust leaves a URL without {nonce} unchanged (client). By
	// default such a URL gets the NonceParam query parameter with a random
	// value per request, so that no cache keyed on the target can answer
	// one request with the response to another. Set it for a server or
	// intermediary that refuses unknown query parameters, when nothing on
	// the path caches POST responses; a cached response would still fail
	// its MAC and be repeated, but not get through.
	NoCacheBust bool

	// Header is added to every request (client).
	Header http.Header
	// DownURL is the target template of DOWN requests (client; empty: the
	// URL given to HTTPExchangePipe, which UP and CLOSE requests use). It
	// may differ in scheme, host, port and path and pass other
	// intermediaries, as long as every request of a carrier reaches the
	// server process that holds it; it takes the same placeholders.
	DownURL string
	// Instance replaces {instance} in the URL (client). The default is a
	// random token per carrier, the same in every request of the carrier,
	// so that a load balancer hashing the target keeps a carrier on one
	// server.
	Instance string
	// NonceParam names the query parameter that carries a random value per
	// request when the URL has no {nonce} placeholder ("n"), so that no
	// cache keyed on the target matches (client).
	NonceParam string
	// DownRequests is the number of DOWN requests the client keeps
	// outstanding (2); it is lowered while the server answers BUSY.
	DownRequests int
	// UpRequests bounds the UP requests outstanding at once (2).
	UpRequests int
	// UpPieceSize is the largest UP piece the client sends, and the server's
	// limit when above 1 MiB, the default limit of piece data a request may
	// carry. A request whose Content-Length exceeds that limit plus the
	// largest request header, after the body encoding, is not read: it goes
	// to the fallback (Next) as a request that is not an exchange request.
	// The default (DefaultExchangePieceSize) keeps every request body at
	// most 1,000,000 bytes after the body encoding.
	UpPieceSize int
	// RequestTimeout bounds one attempt of one request (25 s; negative: no timeout); it must
	// exceed the server's HoldTime.
	RequestTimeout time.Duration
	// BackoffMin and BackoffMax bound the randomized, doubling delay
	// before a request without a result is repeated (20 ms, 2 s).
	BackoffMin, BackoffMax time.Duration
	// Deadline fails the carrier when a request has had no result for this
	// long (30 s); zmux then recovers on its own.
	Deadline time.Duration

	// HoldTime bounds how long the server holds a DOWN request without
	// data (20 s).
	HoldTime time.Duration
	// Coalesce is how long a piece waits for more bytes after its first
	// byte while a request can take it. Zero is 2 ms; a negative value
	// sends every piece at once, as httputil.ReverseProxy.FlushInterval
	// does. The client coalesces UP pieces the same way.
	Coalesce time.Duration
	// DownPieceSize is the largest DOWN piece the server sends, and the
	// client's limit when above 1 MiB, the default limit of piece data a
	// response may carry; a larger piece fails the carrier. The default
	// (DefaultExchangePieceSize) keeps every response body at most
	// 1,000,000 bytes after the body encoding.
	DownPieceSize int
	// DownWindow is the number of downlink pieces the server assigns ahead
	// of the client's acknowledgement (32); requests beyond it get BUSY.
	DownWindow int
	// UpStoreLimit bounds the uplink bytes the server holds per carrier
	// (4 MiB; at least twice the largest UP piece accepted). Each piece
	// held out of order also counts a fixed 64 bytes, which bounds how
	// many are held.
	UpStoreLimit int
	// IdleTimeout fails a server carrier without requests (60 s; negative:
	// no timeout).
	IdleTimeout time.Duration
	// GoneMemory is how long the server remembers an ended carrier to
	// answer its late requests with GONE (60 s).
	GoneMemory time.Duration
	// MaxClockSkew is the largest difference between a request's Time and
	// the server's clock that the server accepts (60 s).
	MaxClockSkew time.Duration
	// NonceCacheSize bounds the (Carrier ID, Nonce) pairs the server
	// remembers within the time window (262144); a request that finds it
	// full is not authenticated.
	NonceCacheSize int
	// Next is the handler of the requests the server does not
	// authenticate, and of VerdictFallback (HTTPOptions.Next; nil:
	// http.NotFound). The listener's admission decides on the request
	// that creates a carrier, on its head (CarrierInfo.Head): Peek does
	// not apply.
	Next http.Handler
	// Trusted names the intermediaries whose forwarding header field gives
	// a request's source (HTTPOptions.Trusted).
	Trusted *TrustedProxies
	// contains filtered or unexported fields
}

HTTPExchangeConfig configures both ends of an HTTP exchange carrier. A PSK is required unless AllowInsecure is set; the zero value of every other field selects its default. PSK (or AllowInsecure) and Base64 must be the same on both ends; the other fields are local to one end. The server's HoldTime must stay below the response timeout of every intermediary on the path, and the client's RequestTimeout above the HoldTime.

The MACs authenticate and bind responses to requests, but nothing is encrypted: when TLS is terminated by a proxy or CDN, that intermediary can read the carrier.

Under the Settings rules of the package documentation, a field of 0 selects its default; a negative RequestTimeout, Deadline, HoldTime or IdleTimeout is no timeout, and a negative Coalesce sends every piece at once; another negative value is invalid (ErrInvalidConfig).

type HTTPExchangeHandler added in v1.3.2

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

HTTPExchangeHandler serves HTTP exchange carriers (see HTTPExchangeConfig) into a Listener: every carrier is handed to Listener.HandlePipe as a bidirectional carrier that starts or joins a session. Mount it at the path (or path prefix) that the clients' URL template points to; the request target and headers are otherwise ignored. The bytes it holds for its carriers count against the listener's memory budget.

Once the listener is closed (Listener.Close or Shutdown) or the handler is, a request for a new carrier is answered with GONE, so the client fails it at once. Carriers already serving sessions continue: they end with their sessions, as other carriers do, or all at once with Close.

func NewHTTPExchangeHandler added in v1.3.2

func NewHTTPExchangeHandler(l *Listener, cfg *HTTPExchangeConfig) (*HTTPExchangeHandler, error)

NewHTTPExchangeHandler returns a handler that serves exchange carriers into l. An invalid cfg (nil, without a PSK and AllowInsecure, or with an invalid Admission) is an ErrInvalidConfig error.

func (*HTTPExchangeHandler) Close added in v1.3.2

func (h *HTTPExchangeHandler) Close() error

Close fails every carrier, refuses new requests and returns once the carriers' pipes have ended.

func (*HTTPExchangeHandler) ServeHTTP added in v1.3.2

func (h *HTTPExchangeHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP answers one exchange request. A request that is not an authenticated, fresh exchange request is served by the fallback (HTTPExchangeConfig.Next) with its body replayed, and changes nothing.

type HTTPOptions added in v1.3.2

type HTTPOptions struct {
	// Next serves the requests that are not carriers: VerdictFallback, and
	// requests the adapter does not take (nil: http.NotFound).
	// An HTTP/1.1 request with a body reaches it full duplex
	// (http.ResponseController.EnableFullDuplex), so its response can go
	// out while the client still streams the body.
	Next http.Handler
	// Trusted names the intermediaries whose forwarding header field gives
	// a request's source (nil: the request's peer is its source). Without
	// it zmux takes r.RemoteAddr as it finds it, so a host that resolves
	// the source itself rewrites r.RemoteAddr before the handler runs and
	// leaves Trusted nil.
	Trusted *TrustedProxies
}

HTTPOptions configure the HTTP adapters (NewHTTPHandler, the exchange handler, and HTTP upgrades such as WebSocket and WebTransport); the admission they run is their listener's (ListenerConfig.Admission).

func (*HTTPOptions) Fallback added in v1.3.2

func (o *HTTPOptions) Fallback(w http.ResponseWriter, r *http.Request)

Fallback serves r with Next (http.NotFound without one). An HTTP/1.1 request with a body reaches Next full duplex (see serveFallback).

func (*HTTPOptions) Validate added in v1.3.2

func (o *HTTPOptions) Validate() error

Validate checks o (nil is valid); the HTTP adapters call it when they are set up.

type HTTPRedirectError added in v1.3.2

type HTTPRedirectError struct {
	StatusCode int
	Location   string
	Reason     string
}

HTTPRedirectError reports a redirect that an HTTP carrier did not follow: to another host, from https to http, one that would change a POST into a GET, past the bound, or without a valid Location.

func (*HTTPRedirectError) Error added in v1.3.2

func (e *HTTPRedirectError) Error() string

type HTTPStatusError added in v1.3.2

type HTTPStatusError struct {
	StatusCode int
	Status     string // as the response gave it, e.g. "403 Forbidden"
}

HTTPStatusError reports that an HTTP carrier's request was answered with a status other than 2xx.

func (*HTTPStatusError) Error added in v1.3.2

func (e *HTTPStatusError) Error() string

type HTTPTarget added in v1.3.2

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

HTTPTarget is the URL of a carrier candidate and the URL that redirects last led it to: later carriers of the candidate start from the final URL, and DialMode remembers it per server in its CarrierCache. It is safe for concurrent use.

func NewHTTPTarget added in v1.3.2

func NewHTTPTarget(rawURL string) *HTTPTarget

NewHTTPTarget returns a target at rawURL.

func (*HTTPTarget) Base added in v1.3.2

func (t *HTTPTarget) Base() string

Base is the URL the target was made with.

func (*HTTPTarget) Redirected added in v1.3.2

func (t *HTTPTarget) Redirected(final string)

Redirected records the final URL of a carrier that redirects led to.

func (*HTTPTarget) Reset added in v1.3.2

func (t *HTTPTarget) Reset()

Reset starts the next carrier from the base URL again.

func (*HTTPTarget) URL added in v1.3.2

func (t *HTTPTarget) URL() string

URL is the URL the next carrier starts from.

type HandshakeTimeoutError added in v1.3.0

type HandshakeTimeoutError struct{}

HandshakeTimeoutError reports that the peer's transport parameters did not arrive within Config.HandshakeTimeout. It matches ErrHandshakeTimeout, net.ErrClosed and os.ErrDeadlineExceeded.

func (*HandshakeTimeoutError) Error added in v1.3.0

func (e *HandshakeTimeoutError) Error() string

Error describes the timeout.

func (*HandshakeTimeoutError) Is added in v1.3.0

func (e *HandshakeTimeoutError) Is(t error) bool

Is matches ErrHandshakeTimeout, net.ErrClosed and os.ErrDeadlineExceeded.

func (*HandshakeTimeoutError) Timeout added in v1.3.0

func (e *HandshakeTimeoutError) Timeout() bool

Timeout reports true.

type Handshaker added in v1.3.3

type Handshaker interface {
	HandshakeContext(ctx context.Context) error
}

Handshaker is a half whose own handshake may not have run yet: the listener calls HandshakeContext within Config.HandshakeTimeout before admission. It returns nil at once when the handshake has completed. A *tls.Conn is one (called only while its handshake is incomplete).

type IdleTimeoutError added in v1.3.0

type IdleTimeoutError struct{ Remote bool }

IdleTimeoutError reports the idle timeout; Remote when the peer's timer expired. It matches ErrIdleTimeout, net.ErrClosed and os.ErrDeadlineExceeded.

func (*IdleTimeoutError) Error added in v1.3.0

func (e *IdleTimeoutError) Error() string

Error describes the timeout.

func (*IdleTimeoutError) Is added in v1.3.0

func (e *IdleTimeoutError) Is(t error) bool

Is matches ErrIdleTimeout, net.ErrClosed and os.ErrDeadlineExceeded.

func (*IdleTimeoutError) Timeout added in v1.3.0

func (e *IdleTimeoutError) Timeout() bool

Timeout reports true.

type InboundState added in v1.3.2

type InboundState uint8

InboundState is the state of a pipe's inbound direction (STATE_MACHINE.md 3.2); InboundNone when the pipe has none.

func (InboundState) String added in v1.3.2

func (s InboundState) String() string

String returns the state's name in lower case ("open").

type JoinAuthReason added in v1.3.2

type JoinAuthReason uint8

JoinAuthReason says which kind of join token failed verification.

func (JoinAuthReason) String added in v1.3.2

func (r JoinAuthReason) String() string

String returns "mac" or "mac_carrier_bound", the names of API.md.

type JoinHint added in v1.3.0

type JoinHint struct {
	// Join is the Zmux-Pipe-Join header: an out-of-band PIPE_JOIN.
	Join string
	// Pair is the Zmux-Pipe-Pair header: the pairing token of a split
	// bootstrap (SPEC.md 6.1.1); Uplink says which half this carrier is.
	// A half waits for its partner in one of 64 pairing slots of the
	// listener, at most 8 per Source; without an Admission in front of
	// it, a few sources can hold them all, so a split bootstrap that the
	// open Internet reaches is served with one.
	Pair   string
	Uplink bool
	// Source is the carrier's client address (CarrierInfo.Source), for a
	// host that resolves it itself (zero: the address the carrier arrived
	// from). The adapters set it from TrustedProxies.
	Source netip.AddrPort
	// Admitted is Decision.Value of the admission that accepted the
	// carrier (nil: none). The listener sets it for WrapPipe; a value
	// passed to HandlePipe is replaced.
	Admitted any
}

JoinHint is what a carrier's request said out of band (HTTP headers).

type KeyingMaterialExporter added in v1.3.3

type KeyingMaterialExporter interface {
	ExportKeyingMaterial(label string, context []byte, length int) ([]byte, error)
}

KeyingMaterialExporter is a half that terminates an end-to-end handshake and exports keying material from it (RFC 5705, RFC 8446 Section 7.5 semantics). It returns an error until that handshake has completed. A transform that runs its own handshake implements it on its halves so that PipeAuth.Exporter and PipeOptions.CarrierBound bind to the innermost handshake.

func Exporter added in v1.3.3

func Exporter(p PipeIO) (e KeyingMaterialExporter, ok bool)

Exporter returns the exporter of p: the first half (W, then R) that implements KeyingMaterialExporter, else the TLS handshake this process runs for a ConnectionStater half, read from its ConnectionState when ExportKeyingMaterial is called: one that completed (TerminatedTLS), or one that may still complete (a *tls.Conn, a carrier with early data such as QUIC 0-RTT); ok false: none. It is the only source of the exporters of PipeAuth.Exporter and PipeOptions.CarrierBound. Exporter only finds the exporter; reading it fails while the handshake is incomplete.

type LaneOpener added in v1.3.3

type LaneOpener interface {
	OpenLane(ctx context.Context) (io.WriteCloser, error)
}

LaneOpener is a half whose carrier opens further write lanes (EXTENSIONS.md lanes): each a writer of whole records.

type LaneStats added in v1.3.2

type LaneStats struct {
	Lane             uint64
	PositionSent     uint64 // bytes written on the outbound lane, its first record included
	PositionAcked    uint64 // the position the peer acknowledged on it
	PositionReceived uint64 // the position of the inbound lane
}

LaneStats are the positions of one lane; a direction the lane does not have reports 0.

type Lease added in v1.3.0

type Lease[C comparable] struct {
	// Conn is the connection to open the pipe on.
	Conn C
	// FateGroup is the connection's fate group (set it as the PipeIO's).
	FateGroup uint64
	// contains filtered or unexported fields
}

Lease is one pipe's use of a pooled connection; the adapter releases it when the pipe ends.

func (*Lease[C]) Release added in v1.3.0

func (l *Lease[C]) Release()

Release ends the lease when its pipe ended; the last lease of a retired connection closes it. Release is idempotent.

func (*Lease[C]) Retire added in v1.3.0

func (l *Lease[C]) Retire()

Retire stops giving new pipes to the lease's connection (for example after it failed); it closes once its pipes are released.

type Limiter added in v1.3.0

type Limiter interface {
	// Ready waits until at least minBytes bytes (or the limiter's burst, if
	// less) are allowed and returns the allowance, at most maxBytes.
	Ready(ctx context.Context, minBytes, maxBytes int) (int, error)
	// TryReady returns the allowance now, 0 when it would have to wait.
	TryReady(maxBytes int) int
	// Charge accounts n bytes actually forwarded.
	Charge(n int)
}

Limiter lets an external limiter, budget or meter act on bytes that zmux forwards itself (Splice, datagrams). zmux calls it outside every session lock.

type Listener added in v1.3.0

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

Listener is the server side of zmux: it accepts sessions and the pipes that join them (MULTIPATH.md 5.4, 5.5), so it is the way to serve clients that use multipath, resume or split carriers. Serve feeds it the connections of a net.Listener (TCP, or TLS with tls.NewListener); HandlePipe feeds it any other carrier, and NewHTTPHandler HTTP carriers. Accept returns the sessions it started:

l := zmux.NewListener(&zmux.ListenerConfig{Config: cfg})
go l.Serve(ctx, ln)
for {
	conn, err := l.Accept(ctx)
	if err != nil {
		return err
	}
	go handle(conn)
}

Close stops accepting; Shutdown also closes the accepted sessions gracefully. Its lock is a leaf: it never takes a session lock while held.

func NewListener added in v1.3.0

func NewListener(cfg *ListenerConfig) *Listener

NewListener returns a listener; feed it carriers with Serve, HandlePipe or NewHTTPHandler. cfg may be nil. It panics if cfg.InstanceID is longer than MaxInstanceIDLen or a count or MemoryBudget is negative (other than NoMemoryLimit).

func (*Listener) Accept added in v1.3.0

func (l *Listener) Accept(ctx context.Context) (*Conn, error)

Accept returns the next session a carrier started.

func (*Listener) AdmitUpgrade added in v1.3.2

func (l *Listener) AdmitUpgrade(w http.ResponseWriter, r *http.Request, o *HTTPOptions) (*Arrival, bool)

AdmitUpgrade takes r, the request of an HTTP upgrade (WebSocket, WebTransport), as a carrier of l and runs l's admission on its head, before anything is written to w: the decision gets no prefix, CarrierInfo.Head is set, and the body is not read. Its source is what o.Trusted resolves. A request that an intermediary forwarded from TLS early data (Early-Data: 1, RFC 8470), or read before the TLS handshake completed (0-RTT on HTTP/3), is answered 425 (Too Early) first and is no carrier. On VerdictAccept (or without an Admission) it returns the arrival and true: the caller completes the upgrade and hands the carrier on with Arrival.HandlePipe, or calls Arrival.HandshakeFailed. Otherwise it has answered r (VerdictFallback, or a carrier the listener refuses, with o.Next) or ended it (VerdictStall, VerdictClose, which abort the request with http.ErrAbortHandler), and the caller returns.

func (*Listener) Arrive added in v1.3.2

func (l *Listener) Arrive(source, peer netip.AddrPort) (*Arrival, error)

Arrive takes a slot of source for a carrier that arrived from peer (source zero: peer). A source without a free slot, or a closed listener (net.ErrClosed), refuses it (ListenerStats.Refused): the caller closes the carrier without a handshake.

func (*Listener) Close added in v1.3.0

func (l *Listener) Close() error

Close stops the listener at once: Accept returns net.ErrClosed, Serve returns net.ErrClosed and closes its net.Listener, every new carrier is refused, joins and resumptions included, the admissions, handshakes and pairing waits in progress are cancelled, and the memory-pressure watcher stops. It does not block; sessions already started continue, without new pipes from the listener (Shutdown ends them).

func (*Listener) CountSetupFailure added in v1.3.2

func (l *Listener) CountSetupFailure()

CountSetupFailure counts a connection that never became a pipe input (ListenerStats.SetupFailures). Adapters that run their own accept loops call it for a failed TLS handshake or its timeout, a failed HTTP or WebSocket upgrade, or their setup limit; the listener's own serve loops count theirs. A nil l does nothing.

func (*Listener) HandlePipe added in v1.3.0

func (l *Listener) HandlePipe(ctx context.Context, p PipeIO, hint JoinHint) error

HandlePipe classifies a new carrier by its first record (or its hint) and starts a session on it, attaches it to a session as a pipe, or closes it. It blocks for the lifetime of the pipe, so that an HTTP handler stays alive; when ctx ends the pipe is aborted. The carrier takes a slot of its source first (hint.Source, or the remote address of a half: Arrive) and passes the listener's admission (Arrival.HandlePipe). A carrier that is not yet classified, or that joins a session and is not yet verified, also holds a pending slot (ListenerConfig.MaxPending).

func (*Listener) MemoryUsed added in v1.3.0

func (l *Listener) MemoryUsed() int64

MemoryUsed reports the bytes charged to the listener's memory budget, in the unit of ListenerConfig.MemoryBudget.

func (*Listener) Serve added in v1.3.0

func (l *Listener) Serve(ctx context.Context, ln net.Listener) error

Serve accepts connections from ln and hands each one to HandlePipe, in a goroutine of its own, as a carrier that starts or joins a session; the sessions it starts are returned by Accept. With an Admission, a TLS connection completes its handshake first, and VerdictFallback hands the connection to ListenerConfig.Fallback. During Shutdown it keeps serving joins and resumptions. For TLS, pass a listener made by tls.NewListener. Serve closes ln when it returns: when ln.Accept fails, when ctx ends (ctx's error), or when the listener is closed (net.ErrClosed). Cancelling ctx also aborts the carriers Serve handed over, ending their pipes; Shutdown or Close leave them to the sessions.

func (*Listener) Shutdown added in v1.3.0

func (l *Listener) Shutdown(ctx context.Context, code ApplicationErrorCode, msg string) error

Shutdown closes the listener gracefully, as http.Server.Shutdown does: Accept returns net.ErrClosed and new sessions are refused at once, while carriers that join or resume the listener's sessions are still taken (through the same admission); every session it started, accepted or not, is shut down with Conn.Shutdown(ctx, code, msg) in parallel: each sends GOAWAY, lets its open streams finish and closes. Once every session has ended, or ctx has (the remaining sessions are then closed at once and ctx's error is returned), Shutdown calls Close.

func (*Listener) StallDuration added in v1.3.2

func (l *Listener) StallDuration(source netip.AddrPort) time.Duration

StallDuration is the duration of a VerdictStall of l's admission for a carrier from source: in [StallMin, StallMax], and the same for every carrier from one source (aggregated as CarrierInfo.Source says) during l's lifetime. It is HMAC-SHA-256, under a key NewListener drew, of the source, reduced to the interval; no state is kept per source. It is 0 without an Admission.

func (*Listener) Stats added in v1.3.2

func (l *Listener) Stats() ListenerStats

Stats returns the listener's counts. A nil l returns zero counts.

func (*Listener) VariantStats added in v1.3.3

func (l *Listener) VariantStats() []VariantStat

VariantStats returns the admission outcomes by Decision.Variant, a copy sorted by Name, with the bucket of the variants past MaxAdmissionVariants last; their sums are AdmissionStats.Accepted, Fallback, Stalled + StallOverflow and Closed. A nil l returns nil.

type ListenerConfig added in v1.3.0

type ListenerConfig struct {
	// Config is the configuration of the sessions it accepts. Its
	// HandshakeTimeout also bounds how long a carrier of the listener waits
	// for its split-bootstrap partner or for the handshake of a join that
	// arrived in early data.
	Config *Config
	// MaxSuspended bounds the suspended sessions it holds. Zero is 1024;
	// the longest-suspended are closed with ZMUX_RESUME_TIMEOUT.
	MaxSuspended int
	// MaxPending bounds the carriers of the listener that have not been
	// classified, or that join a session and have not passed join
	// verification. Zero is 64; when they are full, a new carrier closes the
	// oldest of them rather than being refused.
	MaxPending int
	// MaxPendingPerSource bounds those carriers per source (zero: 8), together
	// with the carriers an Admission stalls: a new carrier beyond it is
	// refused, and one to be stalled is closed. A source is a client address, its /64
	// prefix for IPv6; deployments behind a carrier-grade NAT raise it.
	// Each half of a split bootstrap holds a slot until it waits for its
	// partner, so split bootstraps need at least 2.
	MaxPendingPerSource int
	// FirstRecordTimeout closes a carrier whose first record does not
	// arrive in time. Zero is 2 s; a negative value is no timeout.
	FirstRecordTimeout time.Duration
	// Backlog is the number of sessions waiting for Accept (zero: 128); a new
	// session beyond it is refused.
	Backlog int
	// InstanceID is encoded at the start of every session locator, for
	// load-balancer stickiness; random bytes fill the rest of the 16-byte
	// locator. At most MaxInstanceIDLen bytes.
	InstanceID []byte
	// AnswerUnknownJoins makes the listener answer an admitted carrier
	// whose well-formed join names a locator that starts with InstanceID
	// but no session here: it writes CONNECTION_CLOSE with
	// ZMUX_RESUME_FAILED and ends the carrier (MULTIPATH.md 5.4), so that
	// a suspended client fails at once instead of at its resume timeout.
	// The carrier still counts as rejected; every other rejected carrier
	// gets no byte, and neither does a carrier without a sending half (a
	// QUIC or WebTransport lane, an HTTP split uplink request). Leave it
	// off where a load balancer can route a join to an instance with the
	// same InstanceID that does not hold its session. It does not change
	// what a carrier that Admission does not accept gets; what a carrier
	// that is not admitted receives depends on the Admission configured
	// (without one every carrier is admitted).
	AnswerUnknownJoins bool
	// MemoryBudget bounds the sum over the listener's sessions of buffered
	// receive data, retained data and session window growth. Zero is
	// 1 GiB; NoMemoryLimit is unlimited. It replaces the sessions' own
	// Config.MemoryBudget. Above it sessions grant no new credit, refuse
	// new peer streams, new sessions and pipes are refused, and suspended
	// sessions are closed, the largest first; normal operation resumes
	// below three quarters of it.
	MemoryBudget int64
	// OnMemoryPressure is called with the bytes in use and the budget when
	// pressure starts (used >= budget) and when it ends, outside every
	// lock, one call at a time; it may close sessions.
	OnMemoryPressure func(used, budget int64)
	// Admission, when set, decides on every carrier of the listener,
	// whatever entry point took it (Serve, HandlePipe, the HTTP, exchange
	// and upgrade handlers, the QUIC and WebTransport adapters), before
	// anything is written on it. The order is the same on every entry:
	// the carrier takes a slot of its source (MaxPendingPerSource), its
	// outer handshake completes (TLS, an HTTP upgrade, QUIC; bounded by
	// Config.HandshakeTimeout), the admission reads its prefix and
	// decides (Admission.PeekTimeout), WrapPipe runs, and the carrier is
	// classified (FirstRecordTimeout) as a join or a new session. NewListener
	// panics if it is invalid (Admission.Validate).
	Admission *Admission
	// Fallback receives the byte-stream carriers that the admission
	// decides on with VerdictFallback, with every byte read replayed
	// (PrefixedConn); nil: they are stalled. It returns when it is done
	// with c, and closes it. HTTP carriers fall back to HTTPOptions.Next.
	Fallback func(ctx context.Context, c net.Conn)
	// WrapPipe, when set, is called once for every carrier the listener
	// takes, whatever fed it (Serve, HandlePipe, the HTTP,
	// exchange and adapter handlers), before the carrier is classified. It
	// returns the PipeIO the listener uses in place of p, such as a layer
	// over PipeConn(p), or p itself. hint is the carrier's: hint.Pair marks
	// one half of a split bootstrap, a p with one half only, which WrapPipe
	// may return as it is.
	//
	// While it runs the carrier holds its pending slot (MaxPending,
	// MaxPendingPerSource; a split half holds a pairing slot only once
	// WrapPipe has returned), and Config.HandshakeTimeout bounds it: ctx
	// ends at that bound or when the carrier is evicted, and p is closed
	// then. FirstRecordTimeout runs from its return. The listener sets p's
	// Carrier, Label and FateGroup on the result, whose halves, Framing,
	// WriteOverhead and Variant are WrapPipe's (p.Variant, the admission's
	// Decision.Variant, stays where the result has none). An error, or the bound, closes p and counts a setup
	// failure (ListenerStats.SetupFailures).
	//
	// A layer must map every write on the PipeIO it returns to exactly
	// one write on p, never merging writes; a WriteMessages call
	// (MessageBatchWriter) counts as one write, which the layer may turn
	// into one write of p.
	WrapPipe func(ctx context.Context, p PipeIO, hint JoinHint) (PipeIO, error)
	// SessionConfig, when set, is called once for every carrier that
	// starts a new session (not for joins), outside every lock, with the
	// carrier's info (Source, Peer, and TLS where this process terminated
	// it, as TerminatedTLS reports) and its admission's Decision.Value.
	// It returns the Config of that session, such as PipeAuth.Exporter
	// where TLS ends here and PipeAuth.DeferredPSK where it ends at an
	// intermediary, or per-session ShapingLimits; nil selects Config.
	// Joins to the session verify with its own Config. The listener-level
	// settings stay the listener's: ListenerConfig.MemoryBudget replaces
	// the returned MemoryBudget as it replaces Config's, the carrier-level
	// bounds (split pairing, the handshake of a join in early data,
	// WrapPipe) use Config.HandshakeTimeout, and the returned Clock must
	// be nil or Config's. A returned Config that violates that or is
	// invalid for a server session (ErrInvalidConfig), an error and a
	// panic close the carrier without a byte, counted as rejected.
	SessionConfig func(ctx context.Context, info *CarrierInfo, admitted any) (*Config, error)
}

ListenerConfig configures a Listener under the Settings rules of the package documentation. These are safety bounds: the zero value of every field selects its stated default. A negative FirstRecordTimeout is no timeout and MemoryBudget NoMemoryLimit unlimited; NewListener panics on any other negative value.

type ListenerStats added in v1.3.2

type ListenerStats struct {
	// Sessions counts sessions started: bootstraps offered to Accept, a
	// split bootstrap once.
	Sessions uint64
	// Joins counts joins accepted into existing sessions, and lanes
	// accepted into their pipes.
	Joins uint64
	// Rejected counts inputs closed without a distinguishable reason:
	// unknown, unauthenticated or replayed joins, lanes that name no pipe,
	// or not zmux at all. Admission verdicts count in Admission.
	Rejected uint64
	// Refused counts inputs refused at a limit: of the listener
	// (MaxPendingPerSource, the memory budget), of the session (a join
	// refused with ZMUX_PIPE_RESOURCE_LIMIT), new sessions during
	// Shutdown, or after the listener was closed.
	Refused uint64
	// TimedOut counts inputs without a first record, or join, within
	// FirstRecordTimeout, and split halves whose other half did not arrive
	// in time.
	TimedOut uint64
	// SetupFailures counts connections never made a pipe input: a failed
	// TLS handshake or its timeout (without an Admission; with one it
	// counts in Admission.HandshakeFailed); the handshake that a join sent in
	// early data waits for, when it fails, times out or its wait is
	// cancelled (that join is then counted nowhere else); an HTTP request
	// answered 425 (Too Early); a failed HTTP or WebSocket upgrade; or the
	// setup limit. Only failures an adapter observes count: a QUIC
	// handshake that fails inside the stack before the connection is
	// accepted is counted nowhere. Adapters with
	// their own accept loops report theirs with CountSetupFailure.
	SetupFailures uint64
	// Admission are the outcomes of ListenerConfig.Admission.
	Admission AdmissionStats
}

ListenerStats are the counts of a listener since it was made (API.md 7.2). The unit is the pipe input handed to the listener: a carrier, a lane, or the two carriers of a split pipe once paired, which are one input (a half never paired is one of its own). Every input whose outcome is known is counted once, in one of the first five fields, so that

Sessions + Joins + Rejected + Refused + TimedOut

is the number of pipe inputs whose outcome is known; SetupFailures counts connections that never became a pipe input. Each count is read on its own: relations between them hold for their final values, not in every snapshot.

type Liveness added in v1.3.3

type Liveness struct {
	// KeepAlivePeriod is Config.KeepAlivePeriod: zero is 15 s, a negative
	// value off, otherwise at least 1 s; the period in effect is capped at
	// half the effective idle timeout.
	KeepAlivePeriod time.Duration
	// SuspectFloor is SchedulerParams.SuspectFloor: zero is 250 ms,
	// otherwise at least 50 ms.
	SuspectFloor time.Duration
	// DeadTimeout is SchedulerParams.DeadTimeout: zero is derived from the
	// RTT, otherwise at least 1 s.
	DeadTimeout time.Duration
	// StandbyProbe is SchedulerParams.StandbyProbe: zero is 1 s, a
	// negative value off, otherwise at least 1 s.
	StandbyProbe time.Duration
	// ProbeInterval is SchedulerParams.ProbeInterval: zero is 15 s, a
	// negative value off, otherwise at least 1 s.
	ProbeInterval time.Duration
	// ProbeJitter is SchedulerParams.ProbeJitter, from 0 to below 1: zero
	// is 0.25; a jitter of 0 takes NoProbeJitter.
	ProbeJitter float64
	// NoProbeJitter makes the jitter 0, the fixed schedule.
	NoProbeJitter bool
}

Liveness are the settings of a session that keep it and its pipes alive and detect their failure: Config.KeepAlivePeriod and the SchedulerParams fields of the same names, with their meanings, their defaults for zero values and their bounds. Conn.SetLiveness replaces them while the session runs.

type MessageBatchWriter added in v1.3.3

type MessageBatchWriter interface {
	WriteMessages(msgs [][]byte) error
}

MessageBatchWriter is an optional capability of a message-framed sending half: WriteMessages writes msgs in order, as len(msgs) WriteMessage calls would, in one call (one flush, one locked hand-over). zmux calls it once per output batch, the batch a byte stream gets in one Write or WriteBuffers. It retains neither msgs nor their contents once it returns. An error means none or some were written; the pipe fails.

type MessageLimitReader added in v1.3.3

type MessageLimitReader interface {
	ReadMessageLimit(limit int) ([]byte, error)
}

MessageLimitReader is an optional capability of a MessageReader: ReadMessageLimit returns the next message when it holds at most limit bytes, and fails with ErrMessageTooLarge for a longer one after reading no more than limit+1 of its bytes into memory (the carrier is then unusable). The admission of a listener reads a first message with it (Admission.Peek, MaxPeek); without it, the message is read whole, up to the carrier's own limit, and then checked.

type MessageReader added in v1.3.0

type MessageReader interface {
	// ReadMessage returns the next whole message.
	ReadMessage() ([]byte, error)
}

MessageReader is the receiving half of a message-framed carrier.

type MessageWriter added in v1.3.0

type MessageWriter interface {
	// WriteMessage writes one whole message.
	WriteMessage(p []byte) error
}

MessageWriter is the sending half of a message-framed carrier.

type Mode added in v1.3.2

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

Mode is how DialMode, or a PipePool, chooses the carrier: ExplicitMode or AutoMode.

func AutoMode added in v1.3.2

func AutoMode(c ...Candidate) Mode

AutoMode chooses among the candidates, in their order of preference (most preferred first).

func ExplicitMode added in v1.3.2

func ExplicitMode(c Candidate) Mode

ExplicitMode dials c only: a failure is reported, never replaced by another kind.

type ModeError added in v1.3.2

type ModeError struct {
	Results []CandidateResult
}

ModeError reports that DialMode found no usable candidate, with the outcome of every one it tried.

func (*ModeError) Error added in v1.3.2

func (e *ModeError) Error() string

func (*ModeError) Unwrap added in v1.3.2

func (e *ModeError) Unwrap() []error

Unwrap returns the candidates' errors.

type ModePolicy added in v1.3.2

type ModePolicy struct {
	// Cache remembers the outcomes per server and local network across
	// dials (nil: a cache private to the session).
	Cache *CarrierCache
	// Key names the server and the local network in Cache, such as the
	// server's URL host with the name of the local network.
	Key string
	// TimerFactor, TimerMin and TimerMax set a candidate's timer: the round
	// trip of opening its carrier times TimerFactor (3), within TimerMin
	// (1 s) and TimerMax (3 s); a zero timer would skip every candidate.
	// Request carriers return before any round
	// trip, so for them the timer is TimerMin.
	TimerFactor        float64
	TimerMin, TimerMax time.Duration
	// Settle is how long a joined pipe of a preferred kind stays joined
	// before the pipes of the kind it replaces are retired (1 s).
	Settle time.Duration
	// DropWindow: a carrier kind whose pipes (or session) fail within this
	// long of being chosen counts as failed, so that the next dials skip it
	// until its backoff expires (30 s).
	DropWindow time.Duration
	// NoJoin turns off establishing on the most robust candidate and
	// joining the preferred ones: the candidates are then tried one after
	// another, in order.
	NoJoin bool
}

ModePolicy is the local policy of AutoMode; the zero value of every field selects its default, and a nil *ModePolicy is all defaults.

type OutboundState added in v1.3.2

type OutboundState uint8

OutboundState is the state of a pipe's outbound direction (STATE_MACHINE.md 3.1); OutboundNone when the pipe has none.

func (OutboundState) String added in v1.3.2

func (s OutboundState) String() string

String returns the state's name in lower case ("active").

type PeerRequest added in v1.3.0

type PeerRequest struct {
	Priority uint64
	Standby  bool
}

PeerRequest is the peer's latest PIPE_STATUS request for the local outbound direction.

type Pick added in v1.3.0

type Pick interface {
	Pick(reqs []PickRequest, pipes []PickPipe, out []PickAnswer)
}

Pick is a custom scheduling policy. It runs outside every lock and must not block. One call carries every stream direction that waits for a decision; it writes one answer per request into out (preset to Wait). An answer names a pipe of pipes by index and how many bytes it covers (0: until it is invalidated by a change of the pipe set, a pipe's state or eligibility).

type PickAnswer added in v1.3.0

type PickAnswer struct {
	Index int
	Bytes uint64
	Wait  bool
}

PickAnswer is the answer for one direction: Index is the chosen pipe's index into the pipes passed to Pick (not its pipe ID), Bytes the bytes it covers (0: until invalidated); Wait holds the direction until the session's next input.

type PickPipe added in v1.3.0

type PickPipe struct {
	Pipe      uint64 // pipe ID
	SRTT      time.Duration
	RTTVar    time.Duration
	Rate      float64 // delivery rate estimate, bytes per second
	Unsent    uint64  // Q_p: handed to the carrier and not taken yet, plus its own unsent count where reported
	InFlight  uint64
	Priority  uint64
	Weight    uint64
	State     OutboundState
	Writable  bool
	Standby   bool
	Saturated bool
	Probation bool
	Eligible  bool // under tier gating: the built-in policies choose among these
	// ShapingActive: a Shaper is active on the pipe.
	ShapingActive bool
	// ShapingWeight is the weight the pipe's Shaper set; 0: none.
	ShapingWeight float64
}

PickPipe is a pipe as a custom policy sees it (values only).

type PickRequest added in v1.3.0

type PickRequest struct {
	Stream       StreamID
	Len          uint64 // bytes ready to place
	EligibleTier uint64 // the most-preferred usable tier
	LastPipe     uint64
	HasLastPipe  bool
	Urgency      Urgency
}

PickRequest is a stream direction waiting for a decision.

type Pipe added in v1.3.0

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

Pipe is one attachment of a session. Its methods are safe for concurrent use; they fail with ErrPipeGone once the attachment is retired.

func HTTPSplitJoin added in v1.3.2

func HTTPSplitJoin(ctx context.Context, c *Conn, client *http.Client, url string, h http.Header, cred Credential, o PipeOptions) ([]*Pipe, error)

HTTPSplitJoin joins a split carrier to c as a further pipe of the session: a downlink GET joined out of band and an uplink POST joined in band, opened at the same time (a split bootstrap's pairing makes pipe pair 0 only). Both get o, with their Direction. ctx bounds the joins; the requests then live until their pipes end. When either join fails the other pipe is aborted.

func (*Pipe) Abort added in v1.3.0

func (p *Pipe) Abort(cause error) error

Abort removes the pipe abruptly: failure, reinjection and PIPE_ABANDON(ZMUX_PIPE_FAILED).

func (*Pipe) Admitted added in v1.3.2

func (p *Pipe) Admitted() any

Admitted returns the Decision.Value of the admission that accepted the pipe's carrier, the one that carried its PIPE_JOIN (or the session's value for the bootstrap pipe, Conn.Admitted). It is nil without one, on the dialing side, and once the session no longer knows the pipe. zmux does not compare it with the session's: a host that requires a join to come from the session's client compares them, in WrapPipe or here.

func (*Pipe) ClearLiveness added in v1.3.3

func (p *Pipe) ClearLiveness() error

ClearLiveness makes the pipe follow the session's liveness settings.

func (*Pipe) ClearProbation added in v1.3.2

func (p *Pipe) ClearProbation() error

ClearProbation returns the base of the pipe's probation to the session's.

func (*Pipe) ClearSendPriority added in v1.3.0

func (p *Pipe) ClearSendPriority() error

ClearSendPriority returns the outbound tier to the peer's request.

func (*Pipe) ClearSendStandby added in v1.3.0

func (p *Pipe) ClearSendStandby() error

ClearSendStandby returns the standby flag to the peer's request.

func (*Pipe) Close added in v1.3.0

func (p *Pipe) Close() error

Close removes the pipe gracefully: PIPE_ABANDON(NO_ERROR) and drain (MULTIPATH.md 8.2). It does not block; the pipe's end is reported by NextEvent.

func (*Pipe) ID added in v1.3.0

func (p *Pipe) ID() uint64

ID returns the pipe ID.

func (*Pipe) Revalidate added in v1.3.0

func (p *Pipe) Revalidate() error

Revalidate sends a PIPE_PING at once; the pipe takes no new stream data until it is acknowledged, while another pipe is usable.

func (*Pipe) SetLiveness added in v1.3.3

func (p *Pipe) SetLiveness(l PipeLiveness) error

SetLiveness replaces the pipe's own liveness settings as a whole (the PipeOptions it was added with included); zero fields follow the session's, and an invalid l is an ErrInvalidConfig error that changes nothing. It takes effect as Conn.SetLiveness does: a pipe already suspect keeps the SuspectFloor and DeadTimeout it turned suspect under. Nothing is sent.

func (*Pipe) SetProbation added in v1.3.0

func (p *Pipe) SetProbation(d time.Duration) error

SetProbation sets the base of the pipe's probation; 0 disables it, and a negative value is invalid (ErrInvalidConfig).

func (*Pipe) SetQualityBand added in v1.3.0

func (p *Pipe) SetQualityBand(b QualityBand) error

SetQualityBand sets the band of this pipe.

func (*Pipe) SetReceivePriority added in v1.3.0

func (p *Pipe) SetReceivePriority(v uint64) error

SetReceivePriority asks the peer to use v for its outbound direction; the request is sent at once as PIPE_STATUS (once the pipe is ACTIVE).

func (*Pipe) SetReceiveStandby added in v1.3.0

func (p *Pipe) SetReceiveStandby(b bool) error

SetReceiveStandby asks the peer to treat its outbound direction as standby (or not).

func (*Pipe) SetSendPriority added in v1.3.0

func (p *Pipe) SetSendPriority(v uint64) error

SetSendPriority sets the tier of the local outbound direction; it wins over the peer's request. Nothing is sent.

func (*Pipe) SetSendStandby added in v1.3.0

func (p *Pipe) SetSendStandby(b bool) error

SetSendStandby makes the local outbound direction standby (or not).

func (*Pipe) SetWeight added in v1.3.0

func (p *Pipe) SetWeight(w uint64) error

SetWeight sets the pipe's weight for the round-robin policies (local).

func (*Pipe) Stats added in v1.3.0

func (p *Pipe) Stats() (PipeStats, bool)

Stats returns the pipe's snapshot; false once the attachment is retired (or the session that ended released it): a read reports the absence rather than an error.

type PipeAuth added in v1.3.0

type PipeAuth struct {
	// PSK is a pre-shared key of at least 16 bytes.
	PSK []byte
	// Exporter derives the join secret from the exporter of the innermost
	// end-to-end handshake on pipe 0 (Exporter: a half implementing
	// KeyingMaterialExporter, or TLS/QUIC this process terminates), read
	// when the peer's parameters arrive; a failed read closes the session
	// with INTERNAL_ERROR. A carrier without an exporter (no TLS, or TLS
	// ended at a proxy, and no transform of its own) makes Start fail with
	// ErrInvalidConfig. An intermediary that terminates TLS on both sides
	// leaves the ends with different exporters, so that joins fail: the
	// binding to the exporter, or a client that pins the server, is what
	// proves the handshake end to end, not the presence of TLS.
	Exporter bool
	// AllowInsecure allows joins without a secret (tests, protected
	// networks). It must not be combined with PSK or DeferredPSK.
	AllowInsecure bool
	// DeferredPSK offers a PSK (the P flag) that the application supplies
	// after establishment with Conn.SetJoinSecret, for example once it
	// authenticated the peer over the session. Until then no join key
	// exists: local joins fail with ErrJoinSecretPending and the peer's
	// joins are held (ConnectionStats.JoinSecretPending) for at most
	// HandshakeTimeout (its default when HandshakeTimeout is no
	// timeout), then closed silently; a session that loses its
	// pipes before the secret cannot resume. It combines with Exporter
	// as a static PSK does, and the peer may have the same bytes as a
	// static PSK. It must not be combined with PSK or AllowInsecure.
	DeferredPSK bool
}

PipeAuth selects the secret sources of joins (MULTIPATH.md 10.1).

type PipeIO added in v1.3.0

type PipeIO struct {
	R       io.ReadCloser
	W       io.WriteCloser
	Framing Framing
	// Carrier is the carrier's kind, which the adapters set on both ends
	// and a Candidate's dial sets to its Kind; 0 for a carrier of no listed
	// kind, such as raw TCP or TLS. The session reports it to its
	// ShaperFactory, in pipe events and in PipeStats.
	Carrier CarrierKind
	// Label names the pipe in statistics.
	Label string
	// FateGroup is the carrier's own fate group (a carrier pool's pipes on
	// one connection share one), used when PipeOptions.FateGroup is 0.
	FateGroup uint64
	// WriteOverhead is the fixed number of bytes that each write call on
	// the carrier adds below it, a hint passed to shaping
	// (ShapedPipe.WriteOverhead) and not checked by zmux; 0: none. A value
	// outside [0, MaxWriteOverhead] is ErrInvalidConfig where the PipeIO
	// is used (Start, AddPipe, the listener's HandlePipe and WrapPipe's
	// result). WrapPipe's result keeps the WriteOverhead it sets.
	WriteOverhead int
	// Variant is a short host label (at most 32 bytes advised) for the
	// transform the carrier runs, "" for none: set by a Candidate
	// (Candidate.Variant), an admission (Decision.Variant) or WrapPipe.
	// zmux only reports it, in pipe events, PipeStats, ShapedPipe and
	// CarrierCache keys; the host bounds the number of variants.
	Variant string
}

PipeIO is a pipe input: at most one receiving half and at most one sending half, at least one of them, each closed by zmux exactly once. Optional capabilities are discovered on the halves (see the interfaces below for each, and for the rules a wrapping transform follows):

  • Aborter on W: used before Close when a pipe fails;
  • BuffersWriter on W: a batch of records in one call;
  • MessageBatchWriter on a message-framed W: a batch of messages in one call;
  • CloseWriter on W: graceful end of the write side;
  • ConnectionStater: the TLS that this process terminates for the carrier (TerminatedTLS, CarrierInfo.TLS); records are built at 16382 bytes on a *tls.Conn;
  • KeyingMaterialExporter: the exporter of the innermost end-to-end handshake, for PipeAuth.Exporter and PipeOptions.CarrierBound (Exporter, which falls back to a terminated TLS state);
  • Handshaker: a handshake the listener runs before admission;
  • CarrierConner and LaneOpener: lanes;
  • EarlyClientCarrier and EarlyServerCarrier on W: carrier early data;
  • DatagramChannel: the carrier's datagram channel (EXTENSIONS.md 6.8);
  • UnsentReporter on W and on a lane's writer: bytes not yet transmitted (a TCP connection, or a TLS one over it, reports the socket's where the platform has a query, Linux SIOCOUTQNSD);
  • RetransReporter on W: bytes retransmitted (a TCP connection, or a TLS one over it, reports the socket's: Linux tcpi_bytes_retrans, Darwin tcpi_txretransmitbytes, Windows SIO_TCP_INFO BytesRetrans, a 32-bit count widened to 64 bits).

A half's Close must interrupt a blocked Read or Write.

func HTTPExchangePipe added in v1.3.2

func HTTPExchangePipe(ctx context.Context, client *http.Client, rawURL string, cfg *HTTPExchangeConfig) (PipeIO, error)

HTTPExchangePipe opens an HTTP exchange carrier (see HTTPExchangeConfig) to the HTTPExchangeHandler at rawURL and returns it as a bidirectional pipe for Start or Conn.AddPipe. It sends nothing before zmux writes; the carrier is ready at once. rawURL may contain {instance} and {nonce} placeholders, anywhere in its path or query. client may be nil (http.DefaultClient); keep its transport's MaxIdleConnsPerHost at least DownRequests+UpRequests so that connections are reused. ctx bounds the setting up: ending it before the first verified response fails the carrier, which otherwise lives until zmux closes it. An invalid cfg (nil, or without a PSK and AllowInsecure) is an ErrInvalidConfig error.

Every request follows redirects as HTTPPipe does; a pure scheme upgrade (CheckHTTPRedirect) is remembered, and the carrier's later requests go to the new origin at once.

func HTTPPipe added in v1.3.0

func HTTPPipe(ctx context.Context, client *http.Client, url string, h http.Header, dir Direction, cred Credential) (PipeIO, error)

HTTPPipe opens a carrier over an HTTP request: dir DirBidirectional sends the request body up and reads the response body (HTTP/2, HTTP/3, or an HTTP/1.1 server with full duplex); DirSendOnly is a POST whose body is the uplink; DirReceiveOnly is a GET whose response body is the downlink. h may carry the Zmux-Pipe-Join value of a Reservation. ctx bounds the setting up: ending it before the request is under way (its body read by the transport, or its response arrived) fails the carrier; after that the request lives until the pipe ends, as for any dialled connection.

The PipeIO has the halves of dir only: W alone for DirSendOnly, R alone for DirReceiveOnly. Its Carrier is CarrierStreaming for DirBidirectional and CarrierSplit for a one-way half; the request's protocol is not known yet, so a caller dialing over HTTP/3 sets CarrierHTTP3 itself (zmuxh3.HTTP3Candidate does). Pass a one-way pipe to Conn.AddPipe with the same PipeOptions.Direction, or combine two as HTTPSplitPipe does.

A response status other than 2xx fails the pipe with an *HTTPStatusError: the read half returns it, and for DirSendOnly the write half does once the response arrives. A transport failure is reported the same way.

A redirect is followed as CheckHTTPRedirect allows, up to the bound of client.CheckRedirect (DefaultHTTPRedirects hops when it is nil, which is consulted for every hop); a redirect it refuses fails the pipe with an *HTTPRedirectError. The request is repeated whole at the new URL, with a fresh credential and every uplink byte written so far: until the first response that is not a redirect, the uplink is kept (and, past 64 KiB, held back), so that no byte is lost or sent twice.

cred, when set, is presented for the server's admission: its Prefix starts the request body, and a GET, which has none, carries its Header form. The connection under client is not known when the request is built, so a credential bound to TLS (PrefixAuth.BindTLS) is an error.

func HTTPSplitPipe added in v1.3.0

func HTTPSplitPipe(ctx context.Context, client *http.Client, url string, h http.Header, cred Credential) (PipeIO, error)

HTTPSplitPipe opens a split bootstrap over two requests, a POST uplink and a GET downlink, paired by a random pairing token (SPEC.md 6.1.1), each presenting cred as HTTPPipe does. The carriers must be confidential end to end (TLS to the server).

func NetPipe added in v1.3.0

func NetPipe(c net.Conn) PipeIO

NetPipe returns the PipeIO of a bidirectional net.Conn (TCP, TLS, Unix, or any net.Conn view such as a WebSocket library's).

func PrefixedPipe added in v1.3.2

func PrefixedPipe(p PipeIO, prefix []byte) PipeIO

PrefixedPipe returns p with prefix read before the rest of its receiving half; the sending half, and the carrier capabilities zmux discovers on it, are unchanged. It is how bytes read before HandlePipe are given back.

func StreamPipe added in v1.3.0

func StreamPipe(s *Stream) PipeIO

StreamPipe wraps a bidirectional stream that carries a pipe pair (one the peer opened with PIPE_CARRIER, or any stream the application knows to be a carrier).

type PipeLiveness added in v1.3.3

type PipeLiveness struct {
	// SuspectFloor (at least 50 ms) and DeadTimeout (at least 1 s).
	SuspectFloor time.Duration
	DeadTimeout  time.Duration
	// ProbeInterval is the probe interval of the pipe while it is idle:
	// a negative value turns its idle probes off, otherwise at least 1 s.
	ProbeInterval time.Duration
	// ProbeJitter is from 0 to below 1; a jitter of 0 takes NoProbeJitter.
	ProbeJitter float64
	// NoProbeJitter makes the pipe's jitter 0, the fixed schedule.
	NoProbeJitter bool
}

PipeLiveness are a pipe's own liveness settings, the fields of PipeOptions of the same names with their meanings: a zero field follows the session's (SchedulerParams, Conn.SetLiveness).

type PipeOptions added in v1.3.0

type PipeOptions struct {
	// SendPriority is the tier of the local outbound direction (lower is
	// preferred). nil: the peer's request, else tier 0.
	SendPriority *uint64
	// SendStandby makes the local outbound direction carry data only on
	// failover. nil: the peer's request, else active.
	SendStandby *bool
	// Weight is the share for SpreadRoundRobin and the factor of
	// SpreadRateWeighted. nil: 1; 0 excludes the pipe unless every
	// candidate has 0.
	Weight *uint64
	// Probation is the base of the pipe's probation. Zero is the
	// session's; a negative value is invalid.
	Probation time.Duration
	// Label names the pipe in statistics.
	Label string
	// ReceivePriority is the tier requested for the peer's outbound
	// direction (zero: tier 0).
	ReceivePriority uint64
	// FateGroup groups pipes that share a path; a pipe that replaces a
	// failed one on the same path reuses its fate group. 0: the carrier's
	// PipeIO.FateGroup, else none (an independent path).
	FateGroup uint64
	// SuspectFloor (at least 50 ms) and DeadTimeout (at least 1 s) of the
	// pipe. Zero uses the session's.
	SuspectFloor time.Duration
	DeadTimeout  time.Duration
	// ProbeInterval is the probe interval k of the pipe while it is idle
	// (at least 1 s), measured to the carrier: with a shaping delay of up
	// to H, probes wait k_eff = max(1 s, k - H). Zero uses the session's;
	// a negative value turns the idle probes of the pipe off, as
	// SchedulerParams.ProbeInterval does; otherwise at least 1 s. On an
	// attachment without an outbound direction at the peer at most 15 s
	// takes effect, and the probes stay.
	ProbeInterval time.Duration
	// ProbeJitter is the probe jitter j of the pipe, from 0 to below 1:
	// each probe waits a uniform draw from [k_eff x (1 - j), k_eff]. Zero
	// uses the session's; a jitter of 0 takes NoProbeJitter.
	ProbeJitter float64
	// NoProbeJitter makes the pipe's j 0, the fixed schedule.
	NoProbeJitter bool
	// NoProbation turns the pipe's probation off; Probation must then be
	// zero.
	NoProbation bool
	// Direction from the local endpoint: DirBidirectional (the zero
	// value), DirSendOnly (an uplink) or DirReceiveOnly (a downlink).
	Direction Direction
	// ReceiveStandby asks the peer to make its outbound direction standby
	// (zero: active).
	ReceiveStandby bool
	// CarrierBound ties the join token to the new carrier's innermost
	// end-to-end handshake (MULTIPATH.md 10.5): its exporter (Exporter),
	// read when AddPipe is called, so the carrier's handshake must have
	// completed by then; the listener reads its own side when the join
	// arrives.
	CarrierBound bool
}

PipeOptions are the options of an attachment. The zero value is a bidirectional pipe that follows the peer's priority requests and the session's defaults.

The Send fields are pointers because nil has its own meaning: the local outbound direction then follows the peer's request (PIPE_STATUS), which can change at any time; a set value, the zero value included, wins over it. Weight is a pointer because 0 is a weight of its own (excluded). Set a pointer field with new, as in SendStandby: new(true) or Weight: new(uint64(0)). The Receive fields are plain values because they are always sent: the PIPE_JOIN carries a request for the peer's outbound direction, so the zero values ask for tier 0, not standby.

type PipePool added in v1.3.0

type PipePool struct {
	// Dial opens a carrier of the path. Its context bounds the dial and
	// ends once the join completes; the carrier then lives until the pipe
	// is closed.
	Dial func(ctx context.Context) (PipeIO, error)
	// Join, in place of Dial, joins the pipes of one member of the path
	// itself, such as an uplink and a downlink of a split carrier
	// (HTTPSplitJoin), with the options given; the member is usable while
	// all of them are, and they are replaced together. ctx bounds the
	// joins.
	Join func(ctx context.Context, c *Conn, o PipeOptions) ([]*Pipe, error)
	// Mode, in place of Dial and Join, dials each member over a carrier
	// kind of the mode's candidates (a split candidate joins as a split
	// carrier), presenting the session's Config.Credential. Stable first,
	// then upgrade: a member is dialed over the most robust kind available
	// (a kind ModePolicy.Cache holds as usable, else the exchange carrier,
	// else the last), skipping the kinds the cache holds as failed unless
	// all are; a member of a kind that a preferred kind not backing off
	// could replace is rotated to it, make before break, and the
	// replacement takes over once it has stayed usable for
	// ModePolicy.Settle. A kind whose join fails, whose replacement ends
	// before it settled, or whose member fails within
	// ModePolicy.DropWindow of being joined, is recorded as failed. Each
	// try is reported as an EventCarrierCandidate, and a member joined
	// over a kind other than the session's carrier as an
	// EventCarrierChosen. ExplicitMode dials its one kind only, without
	// the cache.
	Mode Mode
	// ModePolicy is the policy of Mode (nil: the defaults, with a cache
	// private to the pool); its NoJoin does not apply.
	ModePolicy *ModePolicy
	// Count is the number of usable pipes to keep (0: 1, as a pool of no
	// pipes has nothing to maintain).
	Count int
	// Options of the pipes the pool joins.
	Options PipeOptions
	// Rotate replaces pipes that carried MaxBytes or are MaxAge old.
	Rotate Rotation
	// Backoff bounds the redial backoff (from 1 s, at most 60 s), counted
	// from the start of the previous dial attempt, whether it succeeded or
	// failed, or from the start of the pool before its first; each wait is
	// reduced by a random fraction of up to 0.2, drawn once per wait. 0
	// selects the default: no backoff would redial a failing path in a
	// busy loop. A MinBackoff above MaxBackoff (the defaults filled in) is
	// invalid.
	MinBackoff, MaxBackoff time.Duration
	// Policy, when set, is asked on every pass of the pool; its
	// DialAfter replaces the backoff, bounded by MaxBackoff, and its
	// ProbeInterval and ProbeJitter apply to the pipes dialled after it.
	// A decision that fails PoolDecision.Validate is rejected: the pass
	// goes on as with the zero decision and the error is reported to
	// DecisionRejected.
	Policy PoolPolicy
	// DecisionRejected, when set, receives the PoolDecision.Validate error
	// (ErrInvalidConfig) of each decision of Policy the pool rejected, on
	// the goroutine of MaintainPipes and outside every lock; it must not
	// block, and a panic in it is contained. The pool goes on maintaining
	// its pipes whether it is set or not.
	DecisionRejected func(err error)
}

PipePool keeps pipes of one path up.

type PipeStats added in v1.3.0

type PipeStats struct {
	Pipe      uint64 // the pipe ID
	FateGroup uint64
	Label     string
	Variant   string      // PipeIO.Variant
	Local     bool        // this endpoint joined the attachment
	Carrier   CarrierKind // PipeIO.Carrier
	// Outbound and Inbound are the states of the two directions;
	// OutboundNone and InboundNone for one the attachment lacks.
	Outbound     OutboundState
	Inbound      InboundState
	AttachedFor  time.Duration
	SuspectCount uint64 // times the outbound pipe became suspect
	FailureCount uint64 // 0 or 1: whether the attachment failed
	Failure      error  // why it failed, once it did

	// The effective priority and standby flag (Standby, below) of the
	// outbound direction (lower priority preferred) and where they come
	// from: "local", "peer" or "default".
	SendPriority       uint64
	SendPrioritySource string
	StandbySource      string
	// ReceivePriority and ReceiveStandby (below) are requested of the peer
	// for its outbound direction; RequestSeq is the sequence number of the
	// last PIPE_STATUS request sent.
	ReceivePriority uint64
	RequestSeq      uint64
	PeerRequest     *PeerRequest // the peer's latest request; nil before one
	Weight          uint64
	// ProbationUntil is the end of the outbound pipe's probation, zero
	// outside probation or for a base so large that it never ends.
	ProbationUntil time.Time
	Standby        bool
	ReceiveStandby bool
	InProbation    bool
	Revalidating   bool // awaiting revalidation
	Eligible       bool // eligible under tier gating now
	Writable       bool // the outbound carrier takes bytes now
	Saturated      bool // the outbound pipe's tier is saturated

	RTTSource    string        // "ack", "kernel" or "ping"; "" before the first sample
	SmoothedRTT  time.Duration // estimate
	MinRTT       time.Duration // estimate
	RTTVar       time.Duration // estimate
	OneWayDelay  time.Duration // estimate; needs acknowledgements
	DeliveryRate uint64        // R_p in bytes per second, estimate; needs acknowledgements

	// QueuedBytes is a gauge of the bytes the outbound carrier holds
	// unsent, the adapter's unsent count summed over the lanes; 0 where
	// the adapter reports none. QueueDelay is the estimate QueuedBytes /
	// DeliveryRate, 0 when either is.
	QueuedBytes   uint64
	QueueDelay    time.Duration
	BytesInFlight uint64 // gauge: sent and not acknowledged

	// BytesSent and BytesReceived are the outbound and inbound positions
	// over all lanes; BytesAcked the acknowledged outbound position.
	BytesSent       uint64
	BytesReceived   uint64
	BytesAcked      uint64
	RecordsSent     uint64
	RecordsReceived uint64
	// BytesReinjected counts stream bytes sent again elsewhere because
	// this pipe failed or became suspect.
	BytesReinjected uint64
	// BytesLost is the outbound bytes sent and not acknowledged when the
	// pipe failed, over all lanes (BytesSent - BytesAcked at that moment);
	// 0 before a failure and without acknowledgements. They are carrier
	// bytes with frame overhead, sent again elsewhere by reinjection,
	// unlike BytesReinjected, the stream payload sent again. RecordsLost is
	// its estimate in records, BytesLost x RecordsSent / BytesSent rounded
	// up.
	BytesLost   uint64
	RecordsLost uint64
	// BytesRetransmitted is the bytes the carrier itself retransmitted, as
	// its adapter reports them (PipeIO: Retransmitted), sampled at most once
	// a second; 0 when it reports none. Pipes sharing one carrier
	// connection (QUIC streams of one connection) report the connection's
	// count, the same on each. LossRate is the smoothed carrier loss rate:
	// an EWMA (gain 1/8) of the retransmitted bytes per byte sent between
	// samples at least 1 s apart; 0 before the first sample.
	BytesRetransmitted     uint64
	LossRate               float64
	BytesOpportunistic     uint64 // opportunistic copies sent on the outbound pipe
	BytesRedundant         uint64 // redundant copies sent on the outbound pipe
	BytesDuplicateReceived uint64 // duplicate stream bytes received on the inbound pipe
	PingsSent              uint64
	PingsAnswered          uint64 // PIPE_PINGs answered by an acknowledgement

	SinceLastAck     time.Duration
	SinceLastReceive time.Duration
	// SinceLastTraffic is the time since a record carrying a traffic frame
	// (STREAM, RESET_STREAM, RESET_STREAM_AT, STOP_SENDING or DATAGRAM) was
	// sent on the pipe or completely received on it, or since the pipe
	// became live. Probes, acknowledgements, other control frames and
	// padding do not count.
	SinceLastTraffic time.Duration

	// LanesOut and LanesIn are gauges of the lanes of each direction, lane
	// 0 included; LanesRefused counts own outbound lanes refused.
	LanesOut, LanesIn int
	LanesRefused      uint64
	// Lanes are the positions of each lane of a pipe with lanes; nil
	// without, lane 0 then being the pipe itself.
	Lanes []LaneStats
}

PipeStats is a snapshot of one attachment (API.md 7.2). Fields marked estimate are the sender's estimators (SCHEDULER.md 2) and change as samples arrive; a gauge is a current value; the other counts only increase. Each field holds a value it had during the call; the state fields (the direction states, flags, priorities and their sources, probation, the lanes present, Pipe) are read at one point, while relations between counts hold for their final values, not in every snapshot. An absent field is its zero value: an estimate or duration before the first sample, the fields that need acknowledgements when ConnectionState shows pipe acknowledgement not in use, and every field of a direction the attachment does not have, whose state is then OutboundNone or InboundNone.

type PipesLostError added in v1.3.0

type PipesLostError struct{ LastPipeErr error }

PipesLostError reports that the carrier failed or every pipe of a direction was lost without resume. It matches ErrPipesLost and net.ErrClosed and unwraps to the error of the last pipe lost, if any.

func (*PipesLostError) Error added in v1.3.0

func (e *PipesLostError) Error() string

Error describes the loss.

func (*PipesLostError) Is added in v1.3.0

func (e *PipesLostError) Is(t error) bool

Is matches ErrPipesLost and net.ErrClosed.

func (*PipesLostError) Unwrap added in v1.3.0

func (e *PipesLostError) Unwrap() error

Unwrap returns LastPipeErr.

type PoolDecision added in v1.3.2

type PoolDecision struct {
	// Count is the members to keep. Zero is the pool's value (a pool
	// keeps one at least); a negative value is invalid.
	Count int
	// DialAfter is the earliest next dial after the start of the last
	// dial attempt (the start of the pool before the first), in place of
	// the pool's backoff (at most its maximum). Zero is the pool's
	// backoff; a negative value is invalid.
	DialAfter time.Duration
	// Retire lists the members to retire now (a pipe is replaced before
	// it closes).
	Retire []uint64
	// Recheck asks for the next Decide within this time even when nothing
	// else happens. Zero is none; a negative value is invalid. Pools wait
	// at least MinRecheck.
	Recheck time.Duration
	// ProbeInterval, ProbeJitter, DisableIdleProbe and NoProbeJitter are
	// set on the pipes a pool dials after this decision, over its
	// PipeOptions: the zero values keep the pool's (else the session's)
	// settings; DisableIdleProbe turns their idle probes off and
	// NoProbeJitter makes their jitter 0; ProbeInterval is otherwise at
	// least 1 s and ProbeJitter from 0 to below 1. Unlike
	// PipeOptions.ProbeInterval, a negative ProbeInterval is invalid here,
	// as the pool decisions shared by every implementation have it. A pool that dials no pipes ignores
	// valid ones. Validate reports values outside these ranges, which a
	// pool (or Config.RedialPolicy's session) does not clamp: it rejects
	// the whole decision and reports the error to its DecisionRejected
	// callback.
	ProbeInterval    time.Duration
	ProbeJitter      float64
	DisableIdleProbe bool
	NoProbeJitter    bool
}

PoolDecision is the answer to Decide. Its zero value keeps the pool's own behaviour.

func (*PoolDecision) Validate added in v1.3.2

func (d *PoolDecision) Validate() error

Validate reports, with ErrInvalidConfig, a decision with a negative Count, DialAfter or Recheck, a ProbeInterval neither 0 nor at least 1 s, or a ProbeJitter outside [0, 1).

type PoolLimits added in v1.3.0

type PoolLimits struct {
	// MaxPipesPerConnection bounds the pipes on a connection at once
	// (0: 8).
	MaxPipesPerConnection int
	// MaxPipesPerConnectionLifetime bounds the pipes a connection carries
	// over its life (0: unlimited).
	MaxPipesPerConnectionLifetime int
	// MaxConnectionAge stops giving pipes to a connection this old (0:
	// unlimited).
	MaxConnectionAge time.Duration
	// Policy, when set, is asked when a pipe is taken or released, and
	// again after the decision's Recheck; Count
	// is the connections to spread pipes over, Retire retires connections
	// by fate group. Its ProbeInterval and ProbeJitter are not used (the
	// pool dials no pipes), but a decision that fails
	// PoolDecision.Validate is rejected as a whole, as by MaintainPipes:
	// the pool goes on as with the zero decision and reports the error to
	// DecisionRejected.
	Policy PoolPolicy
	// DecisionRejected, when set, receives the PoolDecision.Validate error
	// (ErrInvalidConfig) of each decision of Policy the pool rejected,
	// outside the pool's lock, on the goroutine of the Get, Release or
	// recheck that asked the policy (so calls may run concurrently); it
	// must not block, and a panic in it is contained.
	DecisionRejected func(err error)
}

PoolLimits bound how a carrier pool uses each underlying connection. The zero value selects the defaults.

type PoolMember added in v1.3.2

type PoolMember struct {
	ID  uint64 // pipe ID, or the connection's fate group
	Age time.Duration
	// Idle: for a pipe, its PipeStats.SinceLastTraffic (probes,
	// acknowledgements and padding do not end it); for a connection, 0
	// while it carries pipes, otherwise since its last pipe ended, or
	// since it was established when it never carried one.
	Idle          time.Duration
	Pipes         int    // pipes on the connection; 1 for a pipe
	BytesSent     uint64 // 0 for a connection
	BytesReceived uint64 // 0 for a connection
}

PoolMember is a pipe of a PipePool, or a connection of a CarrierPool.

type PoolPolicy added in v1.3.2

type PoolPolicy interface {
	Decide(v *PoolView, d *PoolDecision)
}

PoolPolicy decides the members a pool keeps and when it dials. Decide must not block; the pool clamps values outside its limits.

type PoolView added in v1.3.2

type PoolView struct {
	Now      time.Time
	Members  []PoolMember
	Failures int       // consecutive failed dials
	LastDial time.Time // zero: none
}

PoolView is the state of a pool.

type PreambleTooLargeError added in v1.3.2

type PreambleTooLargeError struct{ Max int }

PreambleTooLargeError reports a stream preamble (OPEN_INFO, application TLVs and the rest) above the largest the peer accepts, Max bytes encoded: the peer's limit once known or assumed for early data, else the 1024-byte floor every endpoint accepts. The setter that would exceed it returns it and leaves the preamble as it was; a stream whose limit shrank before it was announced fails with it locally, and nothing of it is sent.

func (*PreambleTooLargeError) Error added in v1.3.2

func (e *PreambleTooLargeError) Error() string

Error describes the limit.

type PrefixAuth added in v1.3.2

type PrefixAuth struct {
	// Key is the pre-shared key (required).
	Key []byte
	// Slot is the length of a time slot (required, a whole number of
	// seconds).
	Slot time.Duration
	// BindTLS binds tokens to the carrier's TLS handshake through the
	// exporter (PrefixAuthBinding); tokens are then valid on that carrier
	// only.
	BindTLS bool
	// Skew is the number of slots on either side of the verifier's current
	// slot that it also accepts (0: only the current one).
	Skew int
	// CacheSize bounds the Nonces the verifier remembers while their slot
	// is acceptable (0: 65536, as an empty cache would reject every
	// token); a token that finds it full is rejected.
	CacheSize int
	// HeaderField is the request field of the header form (empty:
	// HeaderPrefixAuth), another name only where an intermediary strips
	// unknown fields.
	HeaderField string
}

PrefixAuth configures prefix authentication tokens. Key, Slot, BindTLS and Header must be the same on both ends; Skew and CacheSize are the verifier's. As a Credential it presents a fresh token on every carrier.

func (*PrefixAuth) Header added in v1.3.2

func (a *PrefixAuth) Header(info *CarrierInfo) (name, value string, err error)

Header returns the header form of a fresh token: the field HeaderField (HeaderPrefixAuth) with the token in base64url without padding.

func (*PrefixAuth) Prefix added in v1.3.2

func (a *PrefixAuth) Prefix(info *CarrierInfo) ([]byte, error)

Prefix returns a fresh token for the current time slot, bound to info.TLS with BindTLS (a carrier without TLS is then an error).

type PrefixAuthVerifier added in v1.3.2

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

PrefixAuthVerifier verifies tokens and rejects each Nonce after its first use. It is safe for concurrent use.

func NewPrefixAuthVerifier added in v1.3.2

func NewPrefixAuthVerifier(a *PrefixAuth) (*PrefixAuthVerifier, error)

NewPrefixAuthVerifier returns a verifier for a; an invalid a is an ErrInvalidConfig error.

func (*PrefixAuthVerifier) Decide added in v1.3.2

func (v *PrefixAuthVerifier) Decide(_ context.Context, info *CarrierInfo, prefix []byte) Decision

Decide is an Admission.Decide that accepts a carrier whose prefix is a valid token, without the token, and returns VerdictFallback otherwise. On a carrier decided on its request head (CarrierInfo.Head) the token is the request's only HeaderField field (HeaderPrefixAuth), 43 characters of base64url without padding, and the decision has no prefix. With BindTLS, a carrier without TLS is not accepted. The Admission's Peek must be PrefixTokenLen; a carrier decided on its request head reads none.

func (*PrefixAuthVerifier) Verify added in v1.3.2

func (v *PrefixAuthVerifier) Verify(token, binding []byte) bool

Verify reports whether token is valid for binding and its Nonce is new.

type QualityBand added in v1.3.0

type QualityBand struct {
	// RTT is the band around the reported smoothed RTT. Zero turns this
	// half off.
	RTT time.Duration
	// RateRatio is the factor around the reported delivery rate. Zero
	// turns this half off.
	RateRatio float64
	// MinInterval is the least time between two events of a pipe. Zero
	// is 1 s; no minimum takes NoMinInterval.
	MinInterval time.Duration
	// NoMinInterval sets no minimum time between events.
	NoMinInterval bool
}

QualityBand asks for EventPipeQualityChanged events: emitted for an outbound pipe when its smoothed RTT leaves +-RTT around the last reported value, or its delivery rate leaves [last/RateRatio, last*RateRatio]; at most one per pipe per MinInterval, the latest values winning. The zero QualityBand reports nothing. A negative or NaN field is invalid (ErrInvalidConfig).

type ReceiveStream added in v1.3.0

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

ReceiveStream is the receiving part of a stream.

func (*ReceiveStream) CancelRead added in v1.3.0

func (s *ReceiveStream) CancelRead(code StreamErrorCode)

CancelRead stops reading.

func (*ReceiveStream) Preamble added in v1.3.0

func (s *ReceiveStream) Preamble() []byte

Preamble returns the peer's OPEN_INFO.

func (*ReceiveStream) PreambleTLVs added in v1.3.0

func (s *ReceiveStream) PreambleTLVs() []TLV

PreambleTLVs returns the application TLVs of the peer's preamble.

func (*ReceiveStream) Read added in v1.3.0

func (s *ReceiveStream) Read(p []byte) (int, error)

Read reads stream data.

func (*ReceiveStream) ReadChunk added in v1.3.0

func (s *ReceiveStream) ReadChunk(ctx context.Context, n int) (Chunk, error)

ReadChunk returns up to n bytes without copying.

func (*ReceiveStream) Reject added in v1.3.0

func (s *ReceiveStream) Reject()

Reject declines the stream before reading it.

func (*ReceiveStream) Replayable added in v1.3.0

func (s *ReceiveStream) Replayable() bool

Replayable reports whether the stream arrived as carrier early data.

func (*ReceiveStream) SetPeerPriority added in v1.3.0

func (s *ReceiveStream) SetPeerPriority(urgency Urgency, incremental bool) error

SetPeerPriority asks the peer to schedule the stream so, as Stream.SetPeerPriority.

func (*ReceiveStream) SetReadDeadline added in v1.3.0

func (s *ReceiveStream) SetReadDeadline(t time.Time) error

SetReadDeadline sets the read deadline.

func (*ReceiveStream) SetReceiveWindow added in v1.3.0

func (s *ReceiveStream) SetReceiveWindow(initial, limit uint64)

SetReceiveWindow sets the stream's initial and maximum receive window.

func (*ReceiveStream) Stats added in v1.3.2

func (s *ReceiveStream) Stats() StreamStats

Stats returns a snapshot of the stream's statistics; a nil s returns the zero snapshot.

func (*ReceiveStream) StreamID added in v1.3.0

func (s *ReceiveStream) StreamID() StreamID

StreamID of a receiving part.

func (*ReceiveStream) WriteTo added in v1.3.0

func (s *ReceiveStream) WriteTo(w io.Writer) (int64, error)

WriteTo implements io.WriterTo like Stream.WriteTo.

type ReplayConfig added in v1.3.3

type ReplayConfig struct {
	// Window is how far a stamp may be from the clock (> 0).
	Window time.Duration
	// Max bounds the keys held (> 0).
	Max int
	// NotBefore rejects stamps before it (ReplayOutside), such as the
	// process start, so that what was sent to an earlier process with an
	// empty filter is not accepted again; zero: none.
	NotBefore time.Time
	// Clock is the filter's clock; nil: the host clock.
	Clock timeshim.Clock
}

ReplayConfig configures a ReplayFilter.

type ReplayFilter added in v1.3.3

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

ReplayFilter remembers keys for a window of time so that each is accepted once (single-use nonces, tokens, request identifiers): Check accepts a key k stamped t when t is within Window of the clock and k was not seen, and records k until t leaves the window, at most 2·Window. At most Max keys are held, and a full filter accepts nothing new. Keys are hashed with a per-filter random seed; expiry costs O(1) per Check and no key is ever scanned. It is safe for concurrent use.

The filter trusts its inputs: authenticate k and t together (t inside the MAC or AEAD that covers k) and call Check only on what verified. An unauthenticated stamp lets a replay pick a fresh t, and unauthenticated keys let anyone fill the filter (ReplayFull) and so refuse every honest key until the window passes.

func NewReplayFilter added in v1.3.3

func NewReplayFilter(c ReplayConfig) (*ReplayFilter, error)

NewReplayFilter returns a filter for c; an invalid c is an ErrInvalidConfig error.

func (*ReplayFilter) Check added in v1.3.3

func (f *ReplayFilter) Check(k []byte, t int64) ReplayVerdict

Check checks k stamped t (Unix milliseconds) and records a fresh k. k may be of any length; the filter retains neither k nor its contents. Both must have been authenticated together before the call.

func (*ReplayFilter) Len added in v1.3.3

func (f *ReplayFilter) Len() int

Len is the number of keys held.

type ReplayVerdict added in v1.3.3

type ReplayVerdict uint8

ReplayVerdict is the outcome of ReplayFilter.Check.

const (
	// ReplayFresh means that the key is new and now recorded.
	ReplayFresh ReplayVerdict = iota
	// ReplaySeen means that the key was seen within its window.
	ReplaySeen
	// ReplayOutside means that the stamp is outside the window of the
	// filter's clock, or before its NotBefore.
	ReplayOutside
	// ReplayFull means that the filter holds Max keys and records nothing new.
	ReplayFull
)

func (ReplayVerdict) String added in v1.3.3

func (v ReplayVerdict) String() string

type Reservation added in v1.3.0

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

Reservation is a pipe reserved for an out-of-band join (MULTIPATH.md 5.3): send Header() with the carrier's request as the Zmux-Pipe-Join header, then Attach the carrier.

func (*Reservation) Attach added in v1.3.0

func (r *Reservation) Attach(ctx context.Context, p PipeIO) (*Pipe, error)

Attach binds the carrier of the reserved pipe and waits until the join is confirmed (see AddPipe).

func (*Reservation) Cancel added in v1.3.0

func (r *Reservation) Cancel()

Cancel abandons the reservation.

func (*Reservation) Header added in v1.3.0

func (r *Reservation) Header() string

Header returns the Zmux-Pipe-Join header value (base64url of the PIPE_JOIN frame, without padding).

type ResponseHeaderer added in v1.3.3

type ResponseHeaderer interface {
	ResponseHeader() http.Header
}

ResponseHeaderer is an optional capability of a client half of an HTTP carrier: the header of the HTTP response that opened it (a WebSocket 101, a streaming or split carrier's response), or of the most recent response (an exchange carrier), as a copy; nil before any response. A host or transform reads outer metadata from it, such as Date as a clock hint; it changes nothing. A transparent transform may forward it.

The header is not authenticated: on plain HTTP or WebSocket anyone on the path, and over TLS any proxy that terminates it, can write or alter it. Never base authentication or authorization on it; a host that takes Date as a clock hint bounds what it accepts (a maximum offset from its own clock, never earlier than a time it already trusts).

type ResumeTimeoutError added in v1.3.0

type ResumeTimeoutError struct{ LastPipeErr error }

ResumeTimeoutError reports that a suspended session found no pipe within the resume grace period. It matches ErrResumeTimeout and net.ErrClosed and unwraps to the error of the last pipe lost, if any.

func (*ResumeTimeoutError) Error added in v1.3.0

func (e *ResumeTimeoutError) Error() string

Error describes the timeout.

func (*ResumeTimeoutError) Is added in v1.3.0

func (e *ResumeTimeoutError) Is(t error) bool

Is matches ErrResumeTimeout and net.ErrClosed.

func (*ResumeTimeoutError) Unwrap added in v1.3.0

func (e *ResumeTimeoutError) Unwrap() error

Unwrap returns LastPipeErr.

type RetransReporter added in v1.3.3

type RetransReporter interface{ Retransmitted() (n uint64, ok bool) }

RetransReporter is a sending half that counts the bytes the carrier has retransmitted; ok false when it cannot tell. Queried as Unsent is, at most once a second (PipeStats.BytesRetransmitted, LossRate).

type Role

type Role uint8

Role is the role argument of Start; the zero value is invalid, so a forgotten role is an error rather than a silent client.

const (
	// RoleClient is the initiator (the endpoint that dialled the carrier).
	RoleClient Role = iota + 1
	// RoleServer is the responder.
	RoleServer
	// RoleAuto negotiates the role with zmux_role (symmetric carriers).
	RoleAuto
)

type Rotation added in v1.3.0

type Rotation struct {
	MaxBytes uint64        // 0: no byte limit
	MaxAge   time.Duration // 0: no age limit
	Jitter   float64       // 0 to 1
}

Rotation replaces pipes before a lifetime limit: when a pipe has carried MaxBytes in either direction or is MaxAge old (each reduced by a random fraction of up to Jitter), a replacement is dialled and joined, and the old pipe is closed gracefully once the replacement is usable (make before break).

type Scheduler added in v1.3.0

type Scheduler interface {
	// contains filtered or unexported methods
}

Scheduler is a scheduling policy of a multipath session. The built-in policies are returned by Affinity, SessionAffinity, SpreadETA, SpreadRoundRobin and SpreadRateWeighted.

Example

ExampleScheduler sets a session's scheduling policy in its Config and changes it while the session runs; it applies once there are several pipes.

package main

import (
	"context"
	"fmt"
	"net"
	"time"

	"github.com/zmuxio/zmux-go"
)

// sessions returns a client and a server session over an in-memory carrier.
func sessions(ctx context.Context, ccfg, scfg *zmux.Config) (client, server *zmux.Conn, err error) {
	a, b := net.Pipe()
	ch := make(chan error, 1)
	go func() {
		var err error
		server, err = zmux.Server(ctx, b, scfg)
		ch <- err
	}()
	client, err = zmux.Client(ctx, a, ccfg)
	if serr := <-ch; err == nil {
		err = serr
	}
	if err != nil {
		if client != nil {
			_ = client.Close()
		}
		if server != nil {
			_ = server.Close()
		}
		return nil, nil, err
	}
	return client, server, nil
}

// closeBoth closes both sessions and waits for their ends.
func closeBoth(a, b *zmux.Conn) {
	_ = a.Close()
	_ = b.Close()
	_ = a.Wait()
	_ = b.Wait()
}

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	cfg := &zmux.Config{Scheduler: zmux.SessionAffinity()} // one active pipe per tier
	client, server, err := sessions(ctx, cfg, nil)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer closeBoth(client, server)

	// Share chunks by weight times measured rate from now on.
	client.SetScheduler(zmux.SpreadRateWeighted())
	fmt.Println(len(client.PipeStats()))
}
Output:
1

func Affinity added in v1.3.0

func Affinity() Scheduler

Affinity binds each stream direction to one pipe (the default).

func Custom added in v1.3.0

func Custom(p Pick) Scheduler

Custom returns a scheduler that asks p.

func SessionAffinity added in v1.3.0

func SessionAffinity() Scheduler

SessionAffinity uses one active pipe per tier.

func SpreadETA added in v1.3.0

func SpreadETA() Scheduler

SpreadETA sends every chunk on the pipe with the earliest arrival.

func SpreadRateWeighted added in v1.3.0

func SpreadRateWeighted() Scheduler

SpreadRateWeighted shares chunks by weight times measured rate.

func SpreadRoundRobin added in v1.3.0

func SpreadRoundRobin() Scheduler

SpreadRoundRobin shares chunks by the pipes' weights.

type SchedulerParams added in v1.3.0

type SchedulerParams struct {
	// SuspectFloor is the least time before a pipe without
	// acknowledgements turns suspect. Zero is 250 ms; otherwise at least
	// 50 ms.
	SuspectFloor time.Duration
	// DeadTimeout is the time after which a suspect pipe fails. Zero is
	// derived from the RTT; otherwise at least 1 s.
	DeadTimeout time.Duration
	// Probation is the base of a pipe's probation. Zero is the default
	// (from the RTT and the pipe's history); a negative value is invalid.
	Probation time.Duration
	// OverflowDelay is how long higher tiers stay saturated before a
	// lower tier takes data. Zero is 1 s; a negative value is invalid.
	OverflowDelay time.Duration
	// StandbyProbe is the probe interval of standby pipes while the
	// session carries traffic. Zero is 1 s; a negative value turns these
	// standby probes off (standby pipes are then probed at the probe
	// interval), as for net.KeepAliveConfig.Interval; otherwise at least
	// 1 s.
	StandbyProbe time.Duration
	// ProbeInterval is the probe interval k of idle pipe pairs, measured
	// to the carrier. Zero is 15 s; a negative value turns these idle
	// probes off, as for net.KeepAliveConfig.Idle, which leaves the
	// PIPE_PING of an answer, the standby probes and the probes of
	// uplinks and downlinks; otherwise at least 1 s.
	ProbeInterval time.Duration
	// ProbeJitter is the probe jitter j, from 0 to below 1 (MULTIPATH.md
	// 7.1): each probe waits a uniform draw from [k_eff x (1 - j), k_eff],
	// the first one of pipe 0 from [0, k_eff]. Zero is 0.25; a jitter of 0
	// takes NoProbeJitter.
	ProbeJitter float64
	// SpreadChunk is the unit the spreading policies split data into. Zero
	// is 16 KiB; a negative value is invalid.
	SpreadChunk int
	// NoProbation turns probation off; Probation must then be zero.
	NoProbation bool
	// NoProbeJitter makes j 0, the fixed schedule.
	NoProbeJitter bool
	// NoRedundancy turns redundancy off.
	NoRedundancy bool
}

SchedulerParams tune multipath scheduling and failure detection, under the rules of Config.

type SendStream

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

SendStream is the sending part of a stream.

func (*SendStream) AddPreambleTLV added in v1.3.0

func (s *SendStream) AddPreambleTLV(t uint64, v []byte) error

AddPreambleTLV adds an application TLV before the first frame.

func (*SendStream) CancelWrite

func (s *SendStream) CancelWrite(code StreamErrorCode)

CancelWrite resets the stream.

func (*SendStream) ClearRedundant added in v1.3.2

func (s *SendStream) ClearRedundant()

ClearRedundant undoes SetRedundant: redundancy follows the session's.

func (*SendStream) Close added in v1.3.0

func (s *SendStream) Close() error

Close finishes the stream (FIN after the buffered data); it never blocks.

func (*SendStream) Flush added in v1.3.3

func (s *SendStream) Flush() error

Flush sends what was written now (Stream.Flush).

func (*SendStream) ReadFrom added in v1.3.0

func (s *SendStream) ReadFrom(r io.Reader) (int64, error)

ReadFrom implements io.ReaderFrom like Stream.ReadFrom.

func (*SendStream) SendCapacity added in v1.3.0

func (s *SendStream) SendCapacity() uint64

SendCapacity returns the bytes the stream could transmit now.

func (*SendStream) SetPreamble added in v1.3.0

func (s *SendStream) SetPreamble(b []byte) error

SetPreamble sets OPEN_INFO before the first frame. A preamble that would exceed the peer's limit is *PreambleTooLargeError.

func (*SendStream) SetPriority added in v1.3.0

func (s *SendStream) SetPriority(urgency Urgency, incremental bool)

SetPriority sets the local scheduling priority, as Stream.SetPriority.

func (*SendStream) SetRedundant added in v1.3.0

func (s *SendStream) SetRedundant(on bool)

SetRedundant turns redundant sending on or off (multipath).

func (*SendStream) SetReliableBoundary added in v1.3.0

func (s *SendStream) SetReliableBoundary()

SetReliableBoundary marks the data written so far as delivered.

func (*SendStream) SetScheduler added in v1.3.0

func (s *SendStream) SetScheduler(p Scheduler)

SetScheduler sets the stream's own scheduling policy (nil: the session's).

func (*SendStream) SetSendBuffer added in v1.3.0

func (s *SendStream) SetSendBuffer(n uint64)

SetSendBuffer bounds the stream's written-but-unreleased bytes.

func (*SendStream) SetWriteDeadline

func (s *SendStream) SetWriteDeadline(t time.Time) error

SetWriteDeadline sets the write deadline.

func (*SendStream) Stats added in v1.3.2

func (s *SendStream) Stats() StreamStats

Stats returns a snapshot of the stream's statistics; a nil s returns the zero snapshot.

func (*SendStream) StreamID

func (s *SendStream) StreamID() StreamID

StreamID of a sending part.

func (*SendStream) TryWriteAll added in v1.3.0

func (s *SendStream) TryWriteAll(p []byte) (bool, error)

TryWriteAll writes all of p now, or nothing.

func (*SendStream) WaitSendCapacity added in v1.3.0

func (s *SendStream) WaitSendCapacity(ctx context.Context, n uint64) (uint64, error)

WaitSendCapacity waits for send capacity (see Stream.WaitSendCapacity).

func (*SendStream) Write added in v1.3.0

func (s *SendStream) Write(p []byte) (int, error)

Write writes p.

func (*SendStream) WriteChunk added in v1.3.0

func (s *SendStream) WriteChunk(ctx context.Context, c Chunk) error

WriteChunk writes a chunk without copying and takes ownership of it.

type ShapedPipe added in v1.3.2

type ShapedPipe struct {
	// ID is the pipe ID.
	ID uint64
	// Carrier is the pipe's carrier kind (PipeIO.Carrier); 0 for a carrier
	// of no listed kind, such as raw TCP or TLS.
	Carrier CarrierKind
	// WriteOverhead is the pipe's PipeIO.WriteOverhead: the fixed number
	// of bytes each carrier write adds below the pipe.
	WriteOverhead int
	// Variant is the pipe's PipeIO.Variant, so that a factory can choose a
	// policy per transform.
	Variant string
}

ShapedPipe is the outbound pipe a ShaperFactory makes a Shaper for.

type ShaperFactory added in v1.3.2

type ShaperFactory func(ShapedPipe) shaping.Shaper

ShaperFactory returns the Shaper of an outbound pipe; nil: the pipe is not shaped. It is called when the pipe's first record is made after the factory was installed, and may be called concurrently for different sessions.

type SpliceDirection added in v1.3.0

type SpliceDirection struct {
	Bytes            uint64 // stream bytes forwarded
	DatagramBytes    uint64 // datagram bytes forwarded
	DatagramsDropped uint64
	End              SpliceEnd // how the direction ended
}

SpliceDirection is the result of one direction of a splice.

type SpliceEnd added in v1.3.2

type SpliceEnd struct {
	Kind SpliceEndKind
	Code StreamErrorCode
}

SpliceEnd is how a direction of a splice ended; Code is the application error code of SpliceReset and SpliceStopped, which travels unchanged to the other side, and 0 for the other kinds.

func (SpliceEnd) String added in v1.3.2

func (e SpliceEnd) String() string

String returns the end's kind, with its code for a reset or a stop ("reset 0x77").

type SpliceEndKind added in v1.3.2

type SpliceEndKind uint8

SpliceEndKind is the event that ended a direction of a splice (API.md A.2): one row of the table of ends.

const (
	SpliceFinished       SpliceEndKind = iota // FIN read upstream and passed on
	SpliceReset                               // the upstream stream was reset with Code
	SpliceStopped                             // the downstream stream was stopped with Code
	SpliceUpstreamLost                        // the upstream stream's session closed or was lost
	SpliceDownstreamLost                      // the downstream stream's session closed or was lost
	SpliceCancelled                           // ctx ended, or the direction's Limiter failed
)

func (SpliceEndKind) String added in v1.3.2

func (k SpliceEndKind) String() string

String returns the kind's name ("finished").

type SpliceOptions added in v1.3.0

type SpliceOptions struct {
	// Chunk is the most one direction holds at once (64 KiB; a splice
	// moves data, so 0 has no other meaning).
	Chunk int
	// AtoB and BtoA limit the two directions (nil: none).
	AtoB, BtoA Limiter
}

SpliceOptions configure Splice.

type SpliceResult added in v1.3.0

type SpliceResult struct {
	AtoB, BtoA SpliceDirection
}

SpliceResult is the result of Splice.

func Splice added in v1.3.0

func Splice(ctx context.Context, a, b *Stream, opts *SpliceOptions) (SpliceResult, error)

Splice forwards two bidirectional streams into each other until both directions have ended: what arrives on a is sent on b and what arrives on b is sent on a, a chunk at a time, without copying and only within the receiving side's credit, so backpressure crosses the relay hop by hop. Ends travel across: FIN finishes the other side, a reset resets it with its code after the bytes below its Reliable Size, a stop stops the upstream, a lost session fails the other side with ZMUX_CARRIER_FAILED, and cancelling ctx ends both with code 0.

Example

ExampleSplice relays a stream of one session into a stream of another, as a proxy does: data, ends and backpressure cross without a copy.

ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// client <-> relay (session A); relay <-> backend (session B).
client, relayA, err := sessions(ctx, nil, nil)
if err != nil {
	fmt.Println(err)
	return
}
defer closeBoth(client, relayA)
relayB, backend, err := sessions(ctx, nil, nil)
if err != nil {
	fmt.Println(err)
	return
}
defer closeBoth(relayB, backend)
go echo(ctx, backend)

res := make(chan zmux.SpliceResult, 1)
go func() {
	in, err := relayA.AcceptStream(ctx)
	if err != nil {
		return
	}
	out, err := relayB.OpenStreamSync(ctx)
	if err != nil {
		in.CancelRead(zmux.StreamCancelled)
		in.CancelWrite(zmux.StreamCancelled)
		return
	}
	r, _ := zmux.Splice(ctx, in, out, nil)
	res <- r
}()

reply, err := roundTrip(ctx, client, "through the relay")
if err != nil {
	fmt.Println(err)
	return
}
r := <-res
fmt.Println(reply)
fmt.Println(r.AtoB.Bytes, r.BtoA.Bytes, r.AtoB.End, r.BtoA.End)
Output:
through the relay
17 17 finished finished

type Stream

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

Stream is a bidirectional stream. Close finishes the sending part only (the quic-go convention); use CancelRead to stop reading.

func (*Stream) AddPreambleTLV added in v1.3.0

func (s *Stream) AddPreambleTLV(t uint64, v []byte) error

AddPreambleTLV adds an application TLV (type 0x1000 to 0x3fff) before the first frame. A preamble that would exceed the peer's limit is *PreambleTooLargeError.

func (*Stream) CancelRead

func (s *Stream) CancelRead(code StreamErrorCode)

CancelRead stops reading with code (STOP_SENDING).

func (*Stream) CancelWrite

func (s *Stream) CancelWrite(code StreamErrorCode)

CancelWrite resets the sending part with code.

func (*Stream) ClearRedundant added in v1.3.2

func (s *Stream) ClearRedundant()

ClearRedundant undoes SetRedundant: the stream's redundancy follows the session's again (SchedulerParams.NoRedundancy; by default urgency 0 to 2 are redundant).

func (*Stream) Close added in v1.3.0

func (s *Stream) Close() error

Close finishes the sending part (FIN after the buffered data); it never blocks and does not stop reading (CancelRead does).

func (*Stream) Context added in v1.3.0

func (s *Stream) Context() context.Context

Context is the session's context: canceled when the session ends, not when the stream does (unlike a quic-go stream's).

func (*Stream) Flush added in v1.3.3

func (s *Stream) Flush() error

Flush sends what was written now: the opening frame at once when the stream has none yet, with the preamble and the data written before it in that one frame, and the rest of the buffered data, as flow control allows. It waits until they were sent or the write deadline passed (os.ErrDeadlineExceeded), and fails as Write does on a reset or closed stream or session; after Close it flushes the FIN as well. Stream credit is reserved by OpenStream, so the opening frame never waits for it. Data written after Flush goes in later frames. Before establishment the opening frame goes as soon as the stream may open (in early data when that is in use); while the first flight is held (EarlyData.HoldFirstFlight) Flush returns at once and the frames leave with the flight. Flush counts as the first frame: preamble settings fail with ErrTooLate after it. It is the explicit way to open a stream on the wire whose peer speaks first; StreamID pins the same way but does not wait.

func (*Stream) PipeCarrier added in v1.3.0

func (s *Stream) PipeCarrier() bool

PipeCarrier reports whether the peer opened the stream as a pipe carrier.

func (*Stream) Preamble added in v1.3.0

func (s *Stream) Preamble() []byte

Preamble returns the OPEN_INFO the peer opened the stream with.

func (*Stream) PreambleTLVs added in v1.3.0

func (s *Stream) PreambleTLVs() []TLV

PreambleTLVs returns the application TLVs of the peer's preamble.

func (*Stream) Read added in v1.3.0

func (s *Stream) Read(p []byte) (int, error)

Read reads stream data; io.EOF only after a FIN that was not reset.

func (*Stream) ReadChunk added in v1.3.0

func (s *Stream) ReadChunk(ctx context.Context, n int) (Chunk, error)

ReadChunk returns up to n bytes without copying; release the chunk, or hand it to WriteChunk, exactly once. A Chunk is a value: do not keep copies of it past that.

func (*Stream) ReadFrom added in v1.3.0

func (s *Stream) ReadFrom(r io.Reader) (int64, error)

ReadFrom implements io.ReaderFrom; it does not finish the stream. It reads r straight into the stream's pooled send blocks (at most one block, 16 KiB, and what the send buffer admits, per Read), with no intermediate buffer, no copy and no allocation once warm; see Chunk for the carrier's copies. Writes to the stream wait while it runs, and Close or CancelWrite meanwhile ends it with their error, discarding the bytes of the Read in progress.

func (*Stream) ReceiveDatagram added in v1.3.0

func (s *Stream) ReceiveDatagram(ctx context.Context) (uint64, []byte, error)

ReceiveDatagram returns the next stream datagram and its context identifier.

func (*Stream) Reject added in v1.3.0

func (s *Stream) Reject()

Reject declines an accepted stream before reading it: both directions end with ZMUX_REJECTED.

func (*Stream) Replayable added in v1.3.0

func (s *Stream) Replayable() bool

Replayable reports whether the stream's opening frame arrived as carrier early data before the handshake completed (treat its request as one an attacker may have repeated).

func (*Stream) SendCapacity added in v1.3.0

func (s *Stream) SendCapacity() uint64

SendCapacity returns the bytes the sending part could transmit now.

func (*Stream) SendDatagram added in v1.3.0

func (s *Stream) SendDatagram(contextID uint64, p []byte) error

SendDatagram sends a stream datagram with an application context identifier (RFC 9297 Context ID); like Conn.SendDatagram it never blocks and drops the oldest queued datagram when the queue is full.

func (*Stream) SendDatagramWait added in v1.3.0

func (s *Stream) SendDatagramWait(ctx context.Context, contextID uint64, p []byte) error

SendDatagramWait sends a stream datagram like SendDatagram, waiting for room in the send queue instead of dropping its oldest entry.

func (*Stream) SetDeadline added in v1.3.0

func (s *Stream) SetDeadline(t time.Time) error

SetDeadline sets both deadlines.

func (*Stream) SetPeerPriority added in v1.3.0

func (s *Stream) SetPeerPriority(urgency Urgency, incremental bool) error

SetPeerPriority asks the peer to schedule its sending part of the stream so: in the preamble before the first frame, PRIORITY_UPDATE after. An urgency above UrgencyLowest is ErrInvalidConfig.

func (*Stream) SetPipeCarrier added in v1.3.0

func (s *Stream) SetPipeCarrier() error

SetPipeCarrier marks the stream as a carrier of another session's pipe before the first frame.

func (*Stream) SetPreamble added in v1.3.0

func (s *Stream) SetPreamble(b []byte) error

SetPreamble sets OPEN_INFO before the first frame. A preamble that would exceed the peer's limit is *PreambleTooLargeError.

Example

ExampleStream_SetPreamble opens a stream with a preamble that names its purpose and a priority, both sent with its first frame.

ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
client, server, err := sessions(ctx, nil, nil)
if err != nil {
	fmt.Println(err)
	return
}
defer closeBoth(client, server)

st, err := client.OpenStreamSync(ctx)
if err != nil {
	fmt.Println(err)
	return
}
// Settings that travel with the first frame come before the first
// Write.
if err := st.SetPreamble([]byte("route=/chat")); err != nil {
	fmt.Println(err)
	return
}
st.SetPriority(zmux.UrgencyHighest, false) // local scheduling
if err := st.SetPeerPriority(zmux.UrgencyHighest, false); err != nil {
	fmt.Println(err) // the peer's scheduling of its answers
	return
}
if _, err := st.Write([]byte("hi")); err != nil {
	fmt.Println(err)
	return
}

peer, err := server.AcceptStream(ctx)
if err != nil {
	fmt.Println(err)
	return
}
fmt.Printf("%s\n", peer.Preamble())
Output:
route=/chat

func (*Stream) SetPriority added in v1.3.0

func (s *Stream) SetPriority(urgency Urgency, incremental bool)

SetPriority sets the local scheduling priority of the stream's sending part: urgency (UrgencyHighest to UrgencyLowest; values above are taken as UrgencyLowest), and whether it is incremental (incremental directions of one urgency share it in turns, the others go one after the other). New streams have UrgencyDefault, incremental.

func (*Stream) SetReadDeadline added in v1.3.0

func (s *Stream) SetReadDeadline(t time.Time) error

SetReadDeadline sets the read deadline.

func (*Stream) SetReceiveWindow added in v1.3.0

func (s *Stream) SetReceiveWindow(initial, limit uint64)

SetReceiveWindow sets the stream's initial and maximum receive window (0 leaves a value; at least 16 KiB).

func (*Stream) SetRedundant added in v1.3.0

func (s *Stream) SetRedundant(on bool)

SetRedundant turns redundant sending of the stream's chunks on or off (multipath; unset, urgency 0 to 2 are redundant).

func (*Stream) SetReliableBoundary added in v1.3.0

func (s *Stream) SetReliableBoundary()

SetReliableBoundary marks the data written so far as delivered even if the stream is reset later (RESET_STREAM_AT).

func (*Stream) SetScheduler added in v1.3.0

func (s *Stream) SetScheduler(p Scheduler)

SetScheduler sets the stream's own scheduling policy (nil: the session's).

func (*Stream) SetSendBuffer added in v1.3.0

func (s *Stream) SetSendBuffer(n uint64)

SetSendBuffer bounds the stream's written-but-unreleased bytes.

func (*Stream) SetWriteDeadline added in v1.3.0

func (s *Stream) SetWriteDeadline(t time.Time) error

SetWriteDeadline sets the write deadline.

func (*Stream) Stats added in v1.3.2

func (s *Stream) Stats() StreamStats

Stats returns a snapshot of the stream's statistics; a nil s returns the zero snapshot.

func (*Stream) StreamID

func (s *Stream) StreamID() StreamID

StreamID returns the identifier; before the first frame it pins it and the opening frame is sent at once (SPEC.md 7.2). Before establishment it is 0. To open a stream on the wire, Flush is the explicit call.

func (*Stream) TryWriteAll added in v1.3.0

func (s *Stream) TryWriteAll(p []byte) (bool, error)

TryWriteAll writes all of p now, or nothing when the send buffer has no room for it.

func (*Stream) WaitSendCapacity added in v1.3.0

func (s *Stream) WaitSendCapacity(ctx context.Context, n uint64) (uint64, error)

WaitSendCapacity waits until SendCapacity is at least n (or above 0 while nothing is unsent) and returns it.

func (*Stream) Write added in v1.3.0

func (s *Stream) Write(p []byte) (int, error)

Write writes p, waiting for send-buffer space.

func (*Stream) WriteChunk added in v1.3.0

func (s *Stream) WriteChunk(ctx context.Context, c Chunk) error

WriteChunk writes a chunk without copying and takes ownership of it.

func (*Stream) WriteTo added in v1.3.0

func (s *Stream) WriteTo(w io.Writer) (int64, error)

WriteTo implements io.WriterTo: it passes w the session's receive buffers in place, with no intermediate buffer.

type StreamError added in v1.3.0

type StreamError struct {
	StreamID  StreamID
	ErrorCode StreamErrorCode
	Remote    bool
	// ReliableSize is the RESET_STREAM_AT Reliable Size of a reset.
	ReliableSize uint64
}

StreamError is a stream ended by the peer: a reset on reads, a STOP_SENDING on writes.

Example

ExampleStreamError shows a stream canceled with a conventional code: the peer sees that code.

package main

import (
	"context"
	"errors"
	"fmt"
	"io"
	"net"
	"time"

	"github.com/zmuxio/zmux-go"
)

// sessions returns a client and a server session over an in-memory carrier.
func sessions(ctx context.Context, ccfg, scfg *zmux.Config) (client, server *zmux.Conn, err error) {
	a, b := net.Pipe()
	ch := make(chan error, 1)
	go func() {
		var err error
		server, err = zmux.Server(ctx, b, scfg)
		ch <- err
	}()
	client, err = zmux.Client(ctx, a, ccfg)
	if serr := <-ch; err == nil {
		err = serr
	}
	if err != nil {
		if client != nil {
			_ = client.Close()
		}
		if server != nil {
			_ = server.Close()
		}
		return nil, nil, err
	}
	return client, server, nil
}

// closeBoth closes both sessions and waits for their ends.
func closeBoth(a, b *zmux.Conn) {
	_ = a.Close()
	_ = b.Close()
	_ = a.Wait()
	_ = b.Wait()
}

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	client, server, err := sessions(ctx, nil, nil)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer closeBoth(client, server)

	st, err := client.OpenStreamSync(ctx)
	if err != nil {
		fmt.Println(err)
		return
	}
	if _, err := st.Write([]byte("x")); err != nil {
		fmt.Println(err)
		return
	}
	peer, err := server.AcceptStream(ctx)
	if err != nil {
		fmt.Println(err)
		return
	}
	st.CancelWrite(zmux.StreamCancelled)

	_, err = io.ReadAll(peer)
	var se *zmux.StreamError
	if errors.As(err, &se) {
		switch se.ErrorCode {
		case zmux.StreamNoError:
			fmt.Println("no error")
		case zmux.StreamCancelled:
			fmt.Println("cancelled by the peer")
		case zmux.StreamRejected, zmux.StreamCarrierFailed:
			fmt.Println("rejected or carrier failed")
		default:
			fmt.Printf("application code %#x\n", uint64(se.ErrorCode))
		}
	}
}
Output:
cancelled by the peer

func (*StreamError) Error added in v1.3.0

func (e *StreamError) Error() string

Error describes the reset or STOP_SENDING.

func (*StreamError) Is added in v1.3.0

func (e *StreamError) Is(t error) bool

Is matches ErrRejected for a peer's ZMUX_REJECTED: the peer did not process the stream, which can be retried (IsRetryable).

type StreamErrorCode added in v1.3.0

type StreamErrorCode uint64

StreamErrorCode is an application error code of a stream.

const (
	StreamNoError       StreamErrorCode = 0
	StreamCancelled     StreamErrorCode = 0x5a4d0001
	StreamRejected      StreamErrorCode = 0x5a4d0002
	StreamCarrierFailed StreamErrorCode = 0x5a4d0003
)

Application error-code conventions (EXTENSIONS.md Section 7).

type StreamID added in v1.3.0

type StreamID int64

StreamID is a stream identifier (RFC 9000 Section 2.1).

type StreamLimitReachedError added in v1.3.0

type StreamLimitReachedError struct{}

StreamLimitReachedError reports that no stream credit is available now (OpenStream); OpenStreamSync waits for credit instead.

func (*StreamLimitReachedError) Error added in v1.3.0

func (e *StreamLimitReachedError) Error() string

Error describes the condition.

func (*StreamLimitReachedError) Temporary added in v1.3.0

func (e *StreamLimitReachedError) Temporary() bool

Temporary reports that credit may arrive later.

type StreamStats added in v1.3.2

type StreamStats struct {
	// BytesWritten counts the payload the sending part accepted from the
	// application; BytesSent the payload put into STREAM frames, every
	// copy (reinjection, redundancy, opportunistic) again.
	BytesWritten, BytesSent uint64
	// BytesAcknowledged counts distinct payload offsets acknowledged:
	// passed to the carrier without multipath, covered by PIPE_ACK with
	// it.
	BytesAcknowledged uint64
	// BytesReceived counts distinct payload bytes received, read or not;
	// none before a peer stream's preamble, and after CancelRead every
	// byte below the highest offset received. BytesRead counts those
	// returned to the application.
	BytesReceived, BytesRead uint64
	// The stream's datagrams handed to a carrier, received and queued,
	// and dropped from its full queue, with their payload bytes.
	DatagramsSent, DatagramsReceived         uint64
	DatagramsDroppedRecv                     uint64
	DatagramBytesSent, DatagramBytesReceived uint64
	// SendBuffered is a gauge of written bytes not yet released (unsent;
	// unacknowledged in multipath), RecvBuffered of received bytes not yet
	// read, RecvWindow of the current receive window.
	SendBuffered, RecvBuffered, RecvWindow uint64
	// PipeID is the pipe the sending direction is bound to under the
	// affinity scheduler while PipeBound is true; pipe 0 is a pipe, so an
	// unbound direction reports PipeBound false (and PipeID 0).
	PipeID    uint64
	PipeBound bool
}

StreamStats is a snapshot of a stream's statistics in payload bytes, the preamble excluded (API.md 7.2); each field holds a value it had during the call, and PipeID with PipeBound are read at one point. Both parts of a bidirectional stream return the same snapshot; the fields of a direction the stream lacks stay 0. Once the session released the stream the snapshot keeps its final values for as long as the handle is held.

type TLV

type TLV struct {
	Type  uint64
	Value []byte
}

TLV is an application TLV of a stream's preamble (EXTENSIONS.md 4.3).

type Tracer added in v1.3.0

type Tracer struct {
	// Established: the peer's transport parameters were processed.
	Established func()
	// Event: a pipe or session event (as NextEvent reports them).
	Event func(Event)
	// Dropped: events lost to overflow since the previous call.
	Dropped func(count uint64)
	// Closed: the session ended; nothing follows.
	Closed func(err error)
}

Tracer receives session events. Its functions run serially and in order on a goroutine of the session, never under a lock; the session never waits for them: a bounded queue holds events, and on overflow the events other than Closed are dropped and counted.

type TransportError added in v1.3.0

type TransportError struct {
	Remote       bool
	ErrorCode    TransportErrorCode
	FrameType    uint64
	ErrorMessage string
	// Details are the key=value pairs of the diagnostic line (SPEC.md 4.3).
	Details string
}

TransportError is a session closed for a protocol error (0x1c).

Example

ExampleTransportError sorts session ends by their transport error code.

package main

import (
	"errors"
	"fmt"

	"github.com/zmuxio/zmux-go"
)

func main() {
	describe := func(err error) string {
		var te *zmux.TransportError
		if !errors.As(err, &te) {
			return "not a transport error"
		}
		switch te.ErrorCode {
		case zmux.TransportNoError:
			return "closed without error"
		case zmux.TransportProtocolViolation, zmux.TransportFrameEncodingError, zmux.TransportFlowControlError,
			zmux.TransportStreamLimitError, zmux.TransportStreamStateError, zmux.TransportFinalSizeError,
			zmux.TransportParameterError, zmux.TransportRoleConflict:
			return "peer misbehaved: " + te.ErrorCode.String()
		case zmux.TransportInternalError, zmux.TransportExcessiveLoad, zmux.TransportConnectionRefused:
			return "peer refused or failed: " + te.ErrorCode.String()
		case zmux.TransportNoViablePath, zmux.TransportResumeTimeout, zmux.TransportResumeFailed, zmux.TransportIdleTimeout:
			return "carriers lost: " + te.ErrorCode.String()
		default:
			return "other: " + te.ErrorCode.String()
		}
	}
	fmt.Println(describe(&zmux.TransportError{Remote: true, ErrorCode: zmux.TransportProtocolViolation}))
	fmt.Println(describe(&zmux.TransportError{Remote: true, ErrorCode: zmux.TransportIdleTimeout}))
}
Output:
peer misbehaved: PROTOCOL_VIOLATION
carriers lost: ZMUX_IDLE_TIMEOUT

func (*TransportError) Error added in v1.3.0

func (e *TransportError) Error() string

Error describes the close.

func (*TransportError) Is added in v1.3.0

func (e *TransportError) Is(t error) bool

Is makes every session termination match net.ErrClosed, and ZMUX_RESUME_FAILED match ErrResumeFailed.

type TransportErrorCode added in v1.3.0

type TransportErrorCode uint64

TransportErrorCode is a transport error code (SPEC.md Section 10.2).

const (
	TransportNoError            TransportErrorCode = 0x00
	TransportInternalError      TransportErrorCode = 0x01
	TransportConnectionRefused  TransportErrorCode = 0x02
	TransportFlowControlError   TransportErrorCode = 0x03
	TransportStreamLimitError   TransportErrorCode = 0x04
	TransportStreamStateError   TransportErrorCode = 0x05
	TransportFinalSizeError     TransportErrorCode = 0x06
	TransportFrameEncodingError TransportErrorCode = 0x07
	TransportParameterError     TransportErrorCode = 0x08
	TransportProtocolViolation  TransportErrorCode = 0x0a
	TransportNoViablePath       TransportErrorCode = 0x10
	TransportExcessiveLoad      TransportErrorCode = 0x25ff75ef
	TransportRoleConflict       TransportErrorCode = 0x277db2c3
	TransportResumeTimeout      TransportErrorCode = 0x0eb87167
	TransportResumeFailed       TransportErrorCode = 0x0f05f74e
	TransportIdleTimeout        TransportErrorCode = 0x2736d55c
)

Transport error codes.

func (TransportErrorCode) String added in v1.3.0

func (c TransportErrorCode) String() string

type TrustedProxies added in v1.3.2

type TrustedProxies struct {
	// Prefixes are the addresses (as /32 or /128 prefixes) and networks of
	// the trusted intermediaries; a peer outside them is its own source.
	Prefixes []netip.Prefix
	// Header is the forwarding header field the trusted intermediaries set
	// on HTTP requests: "X-Forwarded-For", "Forwarded" (RFC 7239),
	// "X-Real-IP", or the name of another field that holds the one client
	// address as X-Real-IP does. Empty: HTTP requests are not read.
	Header string
	// ProxyProtocol makes Listener expect a PROXY protocol header on every
	// connection from a trusted address.
	ProxyProtocol bool
	// contains filtered or unexported fields
}

TrustedProxies names the intermediaries in front of a server (reverse proxies, load balancers, CDNs) whose report of a carrier's client address is believed (MULTIPATH.md 5.6). The source of a carrier, which the admission sees as CarrierInfo.Source and the Listener counts in its per-source limits, is then the client address the intermediary reports; the same report from any other peer is ignored, so that a client cannot choose its own source.

Two mechanisms carry the report, each enabled on its own:

  • PROXY protocol: Listener wraps a net.Listener so that connections from a trusted address start with a PROXY protocol header (version 1 or 2) and report its source as their RemoteAddr. Serve it with Listener.Serve or an http.Server.
  • A forwarding header field on HTTP carriers (Header): set HTTPOptions.Trusted (and HTTPExchangeConfig.Trusted) for the HTTP adapters to read it on requests from a trusted address.

The fields are read when an adapter is set up; a TrustedProxies must not be changed or copied afterwards.

func (*TrustedProxies) Listener added in v1.3.2

func (t *TrustedProxies) Listener(ln net.Listener) net.Listener

Listener returns ln with the PROXY protocol expected from the trusted addresses when ProxyProtocol is set, and ln itself otherwise. A connection from a trusted address that does not start with a header fails its first read; other peers are passed through unread.

func (*TrustedProxies) Source added in v1.3.2

func (t *TrustedProxies) Source(r *http.Request, peer netip.AddrPort) netip.AddrPort

Source returns the client of r, which arrived from peer: the address and port a trusted intermediary in front of the server reports in the Header field (port 0 when it reports none), or peer itself when peer is not trusted, Header is unset, or the field names no client. IPv4-mapped addresses are returned as IPv4, without a zone. A nil t returns peer; an invalid peer is returned as it is. It is the one resolver of the source of an HTTP carrier: the adapters call it and define none of their own.

func (*TrustedProxies) Trusts added in v1.3.2

func (t *TrustedProxies) Trusts(a netip.Addr) bool

Trusts reports whether a is the address of a trusted intermediary: it lies in one of Prefixes (an IPv4-mapped IPv6 address as its IPv4 address). A nil t trusts nobody.

type UnsentReporter added in v1.3.3

type UnsentReporter interface{ Unsent() (n uint64, ok bool) }

UnsentReporter is a sending half (or a lane's writer) that counts the bytes its write calls took that the carrier has not yet transmitted; ok false when it cannot tell. The driver queries it outside the session lock before each write (PipeStats.QueuedBytes, the scheduler's Q_p).

type Urgency added in v1.3.0

type Urgency uint8

Urgency is the scheduling urgency of a stream's sending part (as in RFC 9218): lower is more urgent.

const (
	// UrgencyHighest is the most urgent level.
	UrgencyHighest Urgency = 0
	// UrgencyDefault is the level of a new stream.
	UrgencyDefault Urgency = 3
	// UrgencyLowest is the least urgent level.
	UrgencyLowest Urgency = 7
)

type VariantStat added in v1.3.3

type VariantStat struct {
	// Name is the Decision.Variant ("" for none; also "" for the
	// Overflow bucket).
	Name string
	// Overflow marks the bucket of the variants past MaxAdmissionVariants.
	Overflow bool

	Accepted, Fallback uint64
	// Stalled counts VerdictStall decisions, StallOverflow included.
	Stalled uint64
	Closed  uint64
}

VariantStat are the admission outcomes of one Decision.Variant (Listener.VariantStats).

type Verdict added in v1.3.2

type Verdict uint8

Verdict is the outcome of an admission.

const (
	// VerdictAccept hands the carrier to the Listener, without the first
	// Decision.Skip bytes of the prefix.
	VerdictAccept Verdict = iota
	// VerdictFallback hands the carrier, with every byte read replayed, to
	// the fallback target of its kind (ListenerConfig.Fallback for byte
	// streams, HTTPOptions.Next for HTTP carriers, the QUIC adapter's).
	// Without one a stream carrier is stalled, and an HTTP request gets
	// the server's not-found response.
	VerdictFallback
	// VerdictStall reads and discards what arrives, sends nothing, and
	// closes the carrier gracefully when the peer ends it or after a
	// duration between StallMin and StallMax. A stalled carrier keeps its
	// source's slot (ListenerConfig.MaxPendingPerSource) until it is
	// closed; a source holds at most MaxPendingPerSource - 1 stalled
	// carriers, and one beyond that is closed at once.
	VerdictStall
	// VerdictClose closes the carrier at once.
	VerdictClose
	// VerdictMore asks for a longer prefix of a byte stream: the listener
	// reads until it has Decision.Need bytes, the carrier ends or
	// PeekTimeout passes, and calls Decide again with the longer prefix.
	// Need must exceed the prefix and not exceed MaxPeek, and VerdictMore
	// after a carrier ended short of Need, on a message-framed carrier or
	// on one decided on its request head is VerdictClose.
	VerdictMore
)

Directories

Path Synopsis
adapter
quicmux module
internal
conformance
Package conformance runs the executable traces and the wire corpus of the zmux specification against the sans-IO core (TRACES.md).
Package conformance runs the executable traces and the wire corpus of the zmux specification against the sans-IO core (TRACES.md).
core
Package core is the sans-IO zmux session.
Package core is the sans-IO zmux session.
israce
Package israce reports whether the race detector is on, for tests whose allocation counts it changes.
Package israce reports whether the race detector is on, for tests whose allocation counts it changes.
leakcheck
Package leakcheck verifies that a test leaves no goroutines behind (a standard-library replacement for goleak).
Package leakcheck verifies that a test leaves no goroutines behind (a standard-library replacement for goleak).
wire
Package wire encodes and decodes the zmux wire format: QMux records, frames, transport parameters and stream preambles, with the QUIC variable-length integers of package varint.
Package wire encodes and decodes the zmux wire format: QMux records, frames, transport parameters and stream preambles, with the QUIC variable-length integers of package varint.
seal module
Package shaping defines Shaper, which customizes record sizes and timing.
Package shaping defines Shaper, which customizes record sizes and timing.
machine
Package machine implements a shaping.Shaper driven by state machines read from a Definition.
Package machine implements a shaping.Shaper driven by state machines read from a Definition.
Package varint encodes and decodes QUIC variable-length integers (RFC 9000 Section 16): 1, 2, 4 or 8 bytes, the two high bits of the first byte giving the length, holding values up to 2^62-1.
Package varint encodes and decodes QUIC variable-length integers (RFC 9000 Section 16): 1, 2, 4 or 8 bytes, the two high bits of the first byte giving the length, holding values up to 2^62-1.
zmuxh3 module
zmuxquic module
Package zmuxtest is experimental test support, outside the zmux API stability promise: it may change in any commit and is not for production use.
Package zmuxtest is experimental test support, outside the zmux API stability promise: it may change in any commit and is not for production use.
zmuxws module

Jump to

Keyboard shortcuts

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