zmux

package module
v1.4.7 Latest Latest
Warning

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

Go to latest
Published: Nov 14, 2026 License: Apache-2.0 Imports: 43 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 seal

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 carriers, any message carrier; packages zmuxhttp (HTTP carriers), admit (admission helpers such as PrefixAuth) and carrier (utilities for carrier adapters)
github.com/zmuxio/zmux-go/zmuxquic QUIC carriers
github.com/zmuxio/zmux-go/zmuxh3 HTTP/3 and WebTransport carriers
github.com/zmuxio/zmux-go/zmuxws WebSocket carriers
github.com/zmuxio/zmux-go/seal secure carrier: end-to-end handshake and record protection (experimental)

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 func() { _ = 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. A connection or PipeIO handed to Client, Server, Start, AddPipe or HandlePipe belongs to zmux from then on, whether the call succeeds or fails: zmux closes it, the caller never does. The ctx of Dial, Client and Start bounds establishment only; conn.Context() is the session's own. 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, err := zmux.NewListener(&zmux.ListenerConfig{Config: cfg})
if err != nil {
	return err // the whole configuration is checked here
}
defer func() { _ = l.Close() }()
go func() { _ = 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. Close every listener you made: one that took a carrier runs a goroutine until then. zmux.Server serves a single connection without multipath or resume, and rejects MaxPipes above 1 and ResumeTimeout with ErrInvalidConfig.

In Config and the other configuration structs, the zero value of a field selects its stated default, and a negative value turns the setting off, or makes a limit unlimited, where the field has such a setting; other negative values are invalid. A feature that is on by default has a Switch field (SwitchOff turns it off). A value out of range is ErrInvalidConfig, never corrected. JoinTimeout (10 s) bounds every join and cannot be switched off; HandshakeTimeout bounds establishment only. ListenerConfig.MaxPending (1024 by default) bounds the carriers a listener holds before they belong to a session. Config.Logger (a *slog.Logger) receives the warnings an application would otherwise not see.

Closing

Conn.CloseWithError(code, reason) closes the session gracefully with an application error code and reason, which the peer sees as *zmux.ApplicationError; Conn.Close is CloseWithError(0, ""). It first sends what the streams have written, as far as flow control and the carriers allow, then hands CONNECTION_CLOSE to every usable carrier (written to it; for a socket, taken into the kernel's send buffer). It returns at the latest 1 s after the call, flushing included, so a process may exit as soon as it returns; what was not handed over by then is discarded. Open streams are not waited for; they fail with the session's error. Conn.Abort(code, reason) ends the session at once with an application error and discards unsent data. The first close or abort decides the code and reason; an abort while a close is still flushing ends the flush at once.

Wait waits for the session's whole end: until the peer has read CONNECTION_CLOSE and ended its side of every carrier, or the linger timeout has expired. Done is its selectable form, so "delivered or given up after d" is a select:

_ = conn.CloseWithError(0x2a, "replaced")
select {
case <-conn.Done(): // the peer read the close (or the linger ended)
case <-time.After(5 * time.Second):
}

To let the peer read everything first, including what the open streams still write:

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

Errors

_, err := st.Read(buf)
var app *zmux.ApplicationError
switch {
case zmux.IsRetryable(err):
	// the peer did not process the stream: send it again
case errors.Is(err, zmux.ErrIdleTimeout):
	// the session timed out
case errors.Is(err, zmux.ErrResumeTimeout), errors.Is(err, zmux.ErrPipesLost):
	// every pipe was lost (and not resumed in time); errors.Unwrap(err)
	// is the error of the last pipe lost
	log.Println("paths down:", errors.Unwrap(err))
case errors.As(err, &app) && app.Remote:
	// the peer closed the session with app.ErrorCode
case errors.Is(err, net.ErrClosed):
	// the session ended for another reason
}

Every session end matches net.ErrClosed, the timeouts of a session (ErrIdleTimeout, ErrHandshakeTimeout, ErrResumeTimeout) included; none of them is os.ErrDeadlineExceeded or has a Timeout method, which only a call's own deadline or context has. ErrStreamClosed (an operation on a direction this endpoint closed) matches net.ErrClosed too. ErrResumeFailed is a rejoin the peer refused. ErrInvalidConfig is a configuration error, reported before any byte is written.

Multipath

Both endpoints set MaxPipes above 1 and a join secret; the server uses a Listener. Without a secret source Dial and Start fail with ErrInvalidConfig before writing a byte. 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. Joins need the first pipe known to end at the peer: PipeAuth.EndToEnd declares it in advance (or conn.DeclareEndToEnd later); EndToEnd is no secret source of its own. On a secure first pipe (the seal module) the secure carrier is the source and PipeAuth sets none. 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 ErrJoinPending, whose message says what is missing, the peer's joins wait at most JoinTimeout (ConnectionStats.JoinPending) 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, EndToEnd: true}}
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: zmux.Set(true)})
if err != nil {
	return err
}
for {
	ev, err := conn.NextEvent(ctx)
	if err != nil {
		return err
	}
	if ev.Kind == zmux.EventPipeFailed && ev.PipeID == p.ID() {
		log.Println("backup path failed")
	}
}

The runtime settings in PipeOptions (SendPriority, ReceivePriority, SendStandby, ReceiveStandby, Weight, Probation, Liveness, QualityBand) and its RecordMode are zmux.Change values, the types of PipeUpdate: the zero value follows the peer's request or the default; a zmux.Set(v), zero included, wins, so Weight: zmux.Set(uint64(0)) excludes the pipe from spreading. Direction makes a pipe an uplink (DirectionSendOnly) or a downlink (DirectionReceiveOnly). 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; negative: off). Pipe.Update is the one way to change a live pipe's settings, in one call, each field a zmux.Set(v) or a zmux.Clear that returns it to the peer's request or the session's default:

err := p.Update(zmux.PipeUpdate{SendStandby: zmux.Set(false), Weight: zmux.Clear[uint64]()})

Pipe.Close and Pipe.Abort start a removal and return; Pipe.Wait (and Pipe.Done, its selectable form) returns once the pipe is gone and its carrier's work has ended, with how it ended.

Config.Scheduler picks how records spread over pipes: SchedulerAffinity(), SchedulerSessionAffinity(), SchedulerSpreadETA(), SchedulerSpreadRoundRobin(), SchedulerSpreadRateWeighted() or SchedulerCustom(pick). Every pipe has a PipeID, which events (Event.PipeID) and statistics name. Conn.ReplacePipes(ctx) replaces every pipe through Config.Redial, make before break, after a session secret may have leaked. On the server, zmux.AdmittedAs[T](conn) (or a *Pipe) returns the value the admission attached to the carrier. 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.

Reconnecting after an outage

With ResumeTimeout a session that loses every pipe suspends instead of ending, and resumes when a pipe joins again within the grace period. Something must dial: the Redial hook for a session on one pipe at a time, or MaintainPipes with a PipePool per path for a session that keeps several. Both wait out an exponential backoff from 1 s to 60 s (zmux.Backoff, in Config.RedialBackoff and PipePool.Backoff; jitter 0.2) and any join refusal backoff the peer started. A suspended session with neither reports EventResumeUnattended and logs a warning.

cfg := &zmux.Config{
	ResumeTimeout: 30 * time.Second,
	PipeAuth:      zmux.PipeAuth{PSK: psk, EndToEnd: true},
	Redial: func(ctx context.Context, need zmux.Direction) (zmux.PipeIO, error) {
		var d net.Dialer
		nc, err := d.DialContext(ctx, "tcp", addr)
		if err != nil {
			return zmux.PipeIO{}, err
		}
		return zmux.NetPipe(nc), nil
	},
}
conn, err := zmux.Dial(ctx, "tcp", addr, cfg)
if err != nil {
	return err
}
// The server's Listener uses the same ResumeTimeout and PipeAuth. Streams
// survive a carrier that fails and is redialled within 30 s.

Config.Liveness holds the keep-alive period and the failure-detection and probe settings; Conn.SetLiveness replaces them as a whole while the session runs (zero fields are the defaults, negative ones off, and Conn.Liveness returns the values in effect). A pipe's own PipeLiveness is set with PipeOptions.Liveness, or later with Pipe.Update(zmux.PipeUpdate{Liveness: zmux.Set(pl)}), and dropped with zmux.Clear[zmux.PipeLiveness](). 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. zmux.MaxStreamCredit (2^60) is the largest stream credit, the value of MaxIncomingStreams, MaxIncomingUniStreams and RaiseIncomingStreams that grants as many streams as the protocol counts.

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.NewHandler(l, &zmuxhttp.Options{Next: site})
if err != nil {
	return nil, err
}
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.CarrierCredential and DialPipe DialOptions.CarrierCredential, for an admit.PrefixAuth in its Zmux-Prefix-Auth field, which admit.PrefixAuthVerifier.Decide checks. DialPipe opens a further pipe for AddPipe, and zmuxws.ConnPipe 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 works 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.

Protected carriers (experimental)

The seal module runs a handshake on a session's first carrier and takes the session's secret from it. Each carrier has a record mode (PipeOptions.RecordMode): RecordSealed protects every record end to end where an intermediary terminates the carrier's TLS, RecordBound leaves records to a carrier that protects them and binds its exporter, and RecordTrusted leaves them to the deployment. Further carriers join the session in any mode the acceptor allows. The wire format and the API are experimental and may change.

server := &seal.ServerConfig{Gate: gate, Key: nodeKey}
l, err := zmux.NewListener(&zmux.ListenerConfig{WrapPipe: server}) // validates server
if err != nil {
	return nil, err
}
defer func() { _ = l.Close() }()

ctx, cancel := context.WithTimeout(ctx, 10*time.Second) // a refused handshake gets no reply
defer cancel()
p, err := seal.Establish(ctx, carrier, &seal.ClientConfig{
	Anchor: seal.PinAnchor(seal.NodeKeyID(nodePub)),
	Handle: handle,
	PSK:    psk,
})
if err != nil {
	return nil, err
}
conn, err := zmux.Start(ctx, p, zmux.RoleClient, cfg)

Gate decides who may establish on the server and Anchor whom the client trusts. An Anchor judges the peer's static key, its one opaque credential and the PSK identity, and its VerifyVerdict can require a transcript signature, which makes the peer post-quantum authenticated (RequirePQAuth insists on it). Both ends can exchange opaque application data in the handshake through AppData callbacks. A server refuses silently, so a refused client fails with seal.ErrNoReply; a rejected peer fails with an error matching seal.ErrVerifyRejected, and a verifier that could not judge with one matching seal.ErrVerifyUnavailable.

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 := zmuxhttp.NewExchangeHandler(l, nil, zmuxhttp.ExchangeConfig{PSK: psk})
if err != nil {
	return err
}
defer func() { _ = h.Close() }()
http.Handle("/x/", h)

and the client opens the carrier with the same PSK:

p, err := zmuxhttp.Exchange{Client: client, URL: "https://example.com/x/{instance}/{nonce}",
	Config: zmuxhttp.ExchangeConfig{PSK: psk}}.Pipe(ctx)
if err != nil {
	return err
}
conn, err := zmux.Start(ctx, p, zmux.RoleClient, cfg) // or conn.AddPipe(ctx, p, opts)

zmuxhttp.ExchangeConfig holds what both ends agree on (the PSK, the body encoding, the piece sizes); the client's own settings are the fields of zmuxhttp.Exchange and the server's those of zmuxhttp.ExchangeOptions. {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 ExchangeOptions.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; Exchange and ExchangeOptions document the timers 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. zmuxhttp.Mux classifies each request by its head (zmuxhttp.Options.Classify) 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. The endpoint and its adapters share one zmuxhttp.Options:

o := &zmuxhttp.Options{Next: site, Trusted: trusted}
stream, err := zmuxhttp.NewHandler(l, o)
if err != nil {
	return err
}
ex, err := zmuxhttp.NewExchangeHandler(l, &zmuxhttp.ExchangeOptions{Options: *o}, zmuxhttp.ExchangeConfig{PSK: psk})
if err != nil {
	return err
}
ws, err := zmuxws.NewHandler(l, o)
if err != nil {
	return err
}
http.Handle("/zmux", &zmuxhttp.Mux{Options: o, Stream: stream, Exchange: ex, WebSocket: ws})

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

Choosing a carrier. DialChoice takes a CarrierChoice: ExplicitChoice(c) uses one kind and reports its failure as it is; AutoChoice(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 CarrierChoicePolicy 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 Choice: 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.DialChoice(ctx, zmux.AutoChoice(
	zmuxws.Candidate("wss://example.com/zmux", nil),
	zmuxhttp.Streaming{Client: client, URL: "https://example.com/zmux"}.Candidate(),
	zmuxhttp.Split{Client: client, URL: "https://example.com/zmux"}.Candidate(),
	zmuxhttp.Exchange{Client: client, URL: "https://example.com/zmux", Config: zmuxhttp.ExchangeConfig{PSK: psk}}.Candidate(),
), cfg, &zmux.CarrierChoicePolicy{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 zmuxhttp.Options.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.Liveness.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, zmuxhttp.NewHandler, the exchange handler, zmuxws.NewHandler, zmuxh3.NewHandler and zmuxquic.Serve. Every entry runs the same steps: the carrier takes a slot of the listener (MaxPending) and 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. Its AdmissionVerdict 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, zmuxhttp.Options.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.Adapter().StallDuration). A source is a client address aggregated to its prefix, SourcePrefixV4 bits for IPv4 (default 32, the address on its own) and SourcePrefixV6 bits for IPv6 (default 64), ports ignored; the slots, the stalled-carrier count and the stall duration all use it. ListenerStats.Admission counts the outcomes. An adapter with its own accept loop takes a carrier with Listener.Adapter().Arrive (AdmitUpgrade for an HTTP upgrade) and hands it on with Arrival.HandlePipe; what only such code needs (arrival slots, stall durations, join lookups, memory charging, the listener's timeouts and clock) is on Listener.Adapter() and Conn.Adapter(), not on the objects an application uses. admit.PrefixAuth is one Decide: a carrier starts with a token of admit.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 (admit.HeaderPrefixAuth, 43 characters of base64url). The same Admission serves both:

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

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

A CarrierCredential 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.CarrierCredential; the pipe dialers for joins take theirs in zmuxws.DialOptions.CarrierCredential, zmuxquic.NewConnPool, zmuxh3.NewConnPool and zmuxh3.DialSession; zmuxhttp.Streaming and zmuxhttp.Split 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 (zmuxhttp.Split) 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 (pairing a split bootstrap), counted by the source that MaxPendingPerSource counts (a client by its source prefix). 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 admit.PrefixAuth.

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 (admit.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, ...); 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); admit.ReplayFilter is the single-use cache for its nonces, checked only after the nonce and its timestamp were authenticated together. 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, l, ln, 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 NewConnPool 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 zmuxquic.Client or zmuxquic.ConnPipe stays owned by the caller. zmuxh3.SessionPipe and zmuxh3.StreamPipe do the same for a WebTransport session or stream.

A QUIC close discards stream data the peer has not acknowledged, so a QUIC connection is closed only after the zmux close on its streams was read or given up. The connections zmuxquic.Dial, NewConnPool and Candidate open (and the WebTransport sessions of zmuxh3.NewConnPool and WebTransportCandidate) close once none of their pipes has not ended, each pipe's inbound side having ended or lingered out, with the application error code of the last zmux session they carried (0 after a transport error, an idle timeout or no session). A caller that owns the connection or session closes it after Wait returns (or Done is closed), with the code of the *zmux.ApplicationError that Wait returned; zmuxh3.SessionCloseCode gives it for a WebTransport session.

Datagram queues

Received datagrams wait in bounded queues, the oldest dropped and counted when one is full: the session queue (DatagramReceiveQueue, 128) and the datagrams held for streams not opened yet share DatagramReceiveBytes (1 MiB); each stream's queue has its own count (DatagramStreamQueue, 32) and payload bytes (DatagramStreamBytes, 512 KiB; negative: no byte bound), a single larger datagram being kept alone. An application that forwards packets at a high rate raises both.

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 and zmuxh3.ChannelDropped the 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. zmuxquic.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. zmuxh3.NewServer enables them (zmuxh3.HTTP3Handler wraps the handler of any other HTTP/3 server); both take the zmuxhttp.Options of the zmux handler. Pipes opened with an http.Client, as zmuxh3.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; carrier.ChannelDemux routes the datagrams of a connection shared by several pipes.

Shaping

Config.Shaper, Config.HandshakeShaper, Config.ShapingLimits and Config.ShapingBudget take hooks and bounds for the sizes and timing of what a session writes, and PipePool.Policy, Config.RedialPolicy and carrier.ConnPool.Policy a pool's decisions (packages shaping and shaping/machine, shaping/bundle).

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 zmuxhttp.NewHandler accept any carrier. An Admission on the Listener (ListenerConfig.Admission, admit.PrefixAuth) decides on every carrier before anything is sent on it, whatever entry point took it, and a CarrierCredential is what a client presents for it (Config.CarrierCredential, PresentPipe).

Packages beside this one: zmuxhttp carries sessions over HTTP requests (stream, split and exchange carriers; the exchange carrier, of short requests for paths that buffer or cut long ones, authenticates but does not encrypt, so a proxy or CDN that terminates TLS can read it); admit holds what a server judges a carrier by before any handshake (admit.ClassifyFirstBytes, admit.PrefixAuth, admit.ReplayFilter); carrier holds the building blocks of carrier adapters (a connection pool, a channel datagram demultiplexer). The sub-modules zmuxquic and zmuxh3 carry sessions over QUIC, HTTP/3 and WebTransport, and zmuxws over WebSocket.

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 (admit.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); admit.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). Conn.Close blocks only until the written data is flushed and CONNECTION_CLOSE has been handed to the carriers (at most one second); Conn.Abort, 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 flushes what the streams have written and ends the session, and a process may exit as soon as it returns; Conn.Abort ends it at once with an error code, discarding 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 its sending part with StreamCancelled and stops its receiving part with code 0, so keep it while it is in use. A net.Conn given to Client, Server or a Dial function and a PipeIO given to Start, AddPipe or HandlePipe belong to zmux from then on, whether the call succeeds or fails (ErrInvalidConfig, a refused or failed join, a panic in a host callback included): zmux closes each half exactly once, and the caller never closes 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), and the two that a lost pipe caused unwrap to that pipe's error. A session's end is never a timeout of the call that observed it: none of these matches os.ErrDeadlineExceeded, and none has a Timeout method; only a call's own deadline or context does. 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 (DirectionSendOnly), 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 integer (uint64) bytes per second throughout (PickPipe.Rate, PipeStats.DeliveryRate, Event.DeliveryRate, CapacityFloor.Rate); memory budgets and usage, and byte sizes and limits, are int64 bytes.

Configuration

Settings: each setting is written one way. 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 value is the field's off, none, no timeout or unlimited setting where the field has one, following the standard library (net.Dialer.KeepAlive, http.Server.IdleTimeout): Liveness.KeepAlivePeriod, StandbyProbe and ProbeInterval turn keep-alive and probes off, a negative ProbeJitter is a jitter of 0, a negative MaxIncomingStreams grants no stream, a negative MemoryBudget is unlimited, a negative DatagramStreamBytes leaves a stream's datagram queue without a byte bound, a negative SchedulerParams.Probation turns probation off and a negative zmuxhttp.Exchange.Coalesce sends at once. A negative value of a field without such a setting (JoinTimeout, ResumeTimeout, the windows, MaxPipes) is an error. A feature that is on by default is turned off with a Switch field set to SwitchOff (EpochAfterFirstPipe, SchedulerParams.Redundancy, ...); one that is off by default is a bool named for it (EnableDatagrams, ReturnOnReply). 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). A value out of range is an error, never corrected. Errors are ErrInvalidConfig, from Start, Dial, Client and Server before a byte is written, and from NewListener.

Multipath needs MaxPipes above 1 and a PipeAuth (PSK, DeferredPSK with Conn.SetJoinSecret, or Exporter); a session whose first pipe is not on the secure carrier has join keys only once its host declared that pipe end to end (PipeAuth.EndToEnd or Conn.DeclareEndToEnd). Every added pipe uses the Join handshake. A process restored from a snapshot MUST reseed its random source before any Join: repeated random output can repeat a Reply's nonce, which replays an old confirmation and reuses record keys.

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 (ReadmeAdmission)

Example_readmeAdmission is README.md "Admission".

package main

import (
	"context"
	"crypto/tls"
	"net"
	"time"

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

func main() {
	_ = func(ctx context.Context, key []byte, cfg *zmux.Config, fallback func(context.Context, net.Conn),
		ln net.Listener, tlsConf *tls.Config, addr string) (*zmux.Conn, error) {
		auth := &admit.PrefixAuth{Key: key, Slot: 30 * time.Second, BindTLS: true}
		v, err := admit.NewPrefixAuthVerifier(auth, admit.PrefixAuthVerifierOptions{Skew: 1})
		if err != nil {
			return nil, err
		}
		l, err := zmux.NewListener(&zmux.ListenerConfig{Config: cfg,
			Admission: &zmux.Admission{Peek: admit.PrefixTokenLen, Decide: v.Decide}, Fallback: fallback})
		if err != nil {
			return nil, err
		}
		go func() { _ = l.Serve(ctx, tls.NewListener(ln, tlsConf)) }()

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

Example_readmeClient is README.md "Client".

package main

import (
	"context"
	"io"

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

func main() {
	_ = func(ctx context.Context) ([]byte, error) {
		conn, err := zmux.Dial(ctx, "tcp", "example.com:4433", nil)
		// or: zmux.DialTLS(ctx, "tcp", "example.com:4433", tlsConf, nil)
		if err != nil {
			return nil, err
		}
		defer func() { _ = conn.Close() }()

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

Example_readmeClosing is README.md "Closing".

package main

import (
	"context"
	"time"

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

func main() {
	_ = func(conn *zmux.Conn) error {
		ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
		defer cancel()
		err := conn.Shutdown(ctx, 0, "")
		return err
	}
}
Example (ReadmeErrors)

Example_readmeErrors is README.md "Errors".

package main

import (
	"errors"
	"log"
	"net"

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

func main() {
	_ = func(st *zmux.Stream, buf []byte) {
		_, err := st.Read(buf)
		var app *zmux.ApplicationError
		switch {
		case zmux.IsRetryable(err):
			// the peer did not process the stream: send it again
		case errors.Is(err, zmux.ErrIdleTimeout):
			// the session timed out
		case errors.Is(err, zmux.ErrResumeTimeout), errors.Is(err, zmux.ErrPipesLost):
			// every pipe was lost (and not resumed in time); errors.Unwrap(err)
			// is the error of the last pipe lost
			log.Println("paths down:", errors.Unwrap(err))
		case errors.As(err, &app) && app.Remote:
			// the peer closed the session with app.ErrorCode
		case errors.Is(err, net.ErrClosed):
			// the session ended for another reason
		}
	}
}
Example (ReadmeHTTPExchange)

Example_readmeHTTPExchange is README.md "HTTP exchanges".

package main

import (
	"context"
	"net/http"

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

func main() {
	_ = func(l *zmux.Listener, psk []byte) error {
		h, err := zmuxhttp.NewExchangeHandler(l, nil, zmuxhttp.ExchangeConfig{PSK: psk})
		if err != nil {
			return err
		}
		defer func() { _ = h.Close() }()
		http.Handle("/x/", h)
		return nil
	}
	_ = func(ctx context.Context, client *http.Client, psk []byte, cfg *zmux.Config) (*zmux.Conn, error) {
		p, err := zmuxhttp.Exchange{Client: client, URL: "https://example.com/x/{instance}/{nonce}",
			Config: zmuxhttp.ExchangeConfig{PSK: psk}}.Pipe(ctx)
		if err != nil {
			return nil, err
		}
		conn, err := zmux.Start(ctx, p, zmux.RoleClient, cfg) // or conn.AddPipe(ctx, p, opts)
		return conn, err
	}
}
Example (ReadmeMultipath)

Example_readmeMultipath is README.md "Multipath".

package main

import (
	"context"
	"log"
	"net"

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

func main() {
	_ = func(ctx context.Context, psk []byte, primaryAddr, backupAddr string) error {
		cfg := &zmux.Config{MaxPipes: 4, PipeAuth: zmux.PipeAuth{PSK: psk, EndToEnd: true}}
		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: zmux.Set(true)})
		if err != nil {
			return err
		}
		for {
			ev, err := conn.NextEvent(ctx)
			if err != nil {
				return err
			}
			if ev.Kind == zmux.EventPipeFailed && ev.PipeID == p.ID() {
				log.Println("backup path failed")
			}
		}
	}
}
Example (ReadmePipeUpdate)

Example_readmePipeUpdate is README.md "Multipath" (Pipe.Update).

package main

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

func main() {
	_ = func(p *zmux.Pipe) error {
		err := p.Update(zmux.PipeUpdate{SendStandby: zmux.Set(false), Weight: zmux.Clear[uint64]()})
		return err
	}
}
Example (ReadmeProxy)

Example_readmeProxy is README.md "Behind a reverse proxy or CDN" (the parts without WebSocket; zmuxws holds the others).

package main

import (
	"net/http"
	"net/netip"

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

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

	_ = func(endpoint http.Handler) *http.Server {
		srv := &http.Server{Addr: "127.0.0.1:8080", Handler: endpoint, Protocols: new(http.Protocols)}
		srv.Protocols.SetHTTP1(true)
		srv.Protocols.SetUnencryptedHTTP2(true)
		return srv
	}
}
Example (ReadmeRedial)

Example_readmeRedial is README.md "Reconnecting after an outage".

package main

import (
	"context"
	"net"
	"time"

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

func main() {
	_ = func(ctx context.Context, psk []byte, addr string) (*zmux.Conn, error) {
		cfg := &zmux.Config{
			ResumeTimeout: 30 * time.Second,
			PipeAuth:      zmux.PipeAuth{PSK: psk, EndToEnd: true},
			Redial: func(ctx context.Context, need zmux.Direction) (zmux.PipeIO, error) {
				var d net.Dialer
				nc, err := d.DialContext(ctx, "tcp", addr)
				if err != nil {
					return zmux.PipeIO{}, err
				}
				return zmux.NetPipe(nc), nil
			},
		}
		conn, err := zmux.Dial(ctx, "tcp", addr, cfg)
		if err != nil {
			return nil, err
		}
		// The server's Listener uses the same ResumeTimeout and PipeAuth. Streams
		// survive a carrier that fails and is redialled within 30 s.
		return conn, nil
	}
}
Example (ReadmeServer)

Example_readmeServer is README.md "Server".

package main

import (
	"context"
	"io"
	"net"

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

func main() {
	_ = func(ctx context.Context, cfg *zmux.Config) error {
		ln, err := net.Listen("tcp", ":4433")
		if err != nil {
			return err
		}
		l, err := zmux.NewListener(&zmux.ListenerConfig{Config: cfg})
		if err != nil {
			return err // the whole configuration is checked here
		}
		defer func() { _ = l.Close() }()
		go func() { _ = 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()
					}()
				}
			}()
		}
	}
}
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, err := zmux.NewListener(nil)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer func() { _ = l.Close() }()
	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 Liveness.KeepAlivePeriod.
	DefaultKeepAlivePeriod = time.Duration(core.DefaultKeepAlive)
	// DefaultMaxIdleTimeout is the default Config.MaxIdleTimeout.
	DefaultMaxIdleTimeout = time.Duration(core.DefaultIdleTimeout)
	// DefaultProbeJitter is the default Liveness.ProbeJitter.
	DefaultProbeJitter = core.DefaultProbeJitter
	// DefaultJoinTimeout is the default Config.JoinTimeout.
	DefaultJoinTimeout = time.Duration(core.DefaultHandshakeTimeout)
	// DefaultMinBackoff is the default Backoff.Min, the first wait of the
	// redial backoff of the Redial hook (Config.RedialBackoff) and of each
	// pool (PipePool.Backoff); each wait doubles up to the maximum.
	DefaultMinBackoff = time.Second
	// DefaultMaxBackoff is the default Backoff.Max, the longest wait.
	DefaultMaxBackoff = 60 * time.Second
	// DefaultBackoffJitter is the default Backoff.Jitter: each wait is
	// reduced by a random fraction of up to it.
	DefaultBackoffJitter = 0.2
)

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

View Source
const (
	JoinAuthReasonAuth               = JoinAuthReason(core.JoinAuthAEAD)
	JoinAuthReasonMissingField       = JoinAuthReason(core.JoinAuthMissingField)
	JoinAuthReasonBadField           = JoinAuthReason(core.JoinAuthBadField)
	JoinAuthReasonTLVTruncated       = JoinAuthReason(core.JoinAuthTLVTruncated)
	JoinAuthReasonTLVNonMinimal      = JoinAuthReason(core.JoinAuthTLVNonMinimal)
	JoinAuthReasonTLVOrder           = JoinAuthReason(core.JoinAuthTLVOrder)
	JoinAuthReasonTLVUnknownCritical = JoinAuthReason(core.JoinAuthTLVUnknownCritical)
	JoinAuthReasonKex                = JoinAuthReason(core.JoinAuthKex)
)

Reasons of EventJoinAuthFailed: the Hello did not open (auth), its payload did not parse (the error class of the failure), or its key share was refused after the Pipe ID was used (kex).

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 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. Applications with an identity of their own use "qmux-02.<application>" or an identifier of their own.

View Source
const DefaultMaxPacket = 65535

DefaultMaxPacket is the default PacketOptions.MaxPacket.

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 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 MaxStreamCredit int64 = 1 << 60

MaxStreamCredit is the largest stream count credit the encoding allows, 2^60 (RFC 9000 Section 4.6): the value that grants the peer as many streams as the protocol can count, in effect no limit. It is the upper end of the range of Config.MaxIncomingStreams and MaxIncomingUniStreams and of Conn.RaiseIncomingStreams; those settings have no unlimited setting of their own, and their negative value stays "none".

View Source
const MaxUntakenRead = MaxRecordSize + 8 + firstReadChunk

MaxUntakenRead bounds what the listener reads of a byte-stream carrier before it is classified: a whole record of MaxRecordSize with its length, and one read beyond. A CarrierTaker keeps at most this much.

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 QMuxVersion = "draft-02"

QMuxVersion is the QMux version zmux implements, the one ConnectionState reports.

View Source
const SealedMaxRecord = join.MaxMessage - 16

SealedMaxRecord is the largest Sealed record plaintext.

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).
	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.
	// It matches net.ErrClosed.
	ErrStreamClosed error = &localClosedError{"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")
	// ErrJoinPending is returned by joins of a session without join keys yet: a
	// deferred PSK not supplied (Conn.SetJoinSecret), or an Unmanaged first pipe not
	// declared (Conn.DeclareEndToEnd). The error returned wraps it and says
	// which of the two, or both, is missing.
	ErrJoinPending = errors.New("zmux: join pending")
	// ErrJoinRefused is returned by AddPipe when the peer's Reply refused the join.
	ErrJoinRefused = errors.New("zmux: join refused")
	// ErrCarrierRefused matches an error by which the server or an
	// intermediary refused a carrier, such as an HTTP status other than 2xx
	// or a redirect not followed; a carrier choice counts the try as refused.
	ErrCarrierRefused = errors.New("zmux: carrier refused")
	// 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.

View Source
var (
	// ErrPacketTooLarge is returned for a packet above MaxPacket.
	ErrPacketTooLarge = errors.New("zmux: packet above MaxPacket")
	// ErrMalformedPacket is returned once a PacketStream received bytes
	// that are not a valid capsule sequence (a capsule above MaxPacket, or
	// the stream ending inside a capsule); the stream was reset and
	// stopped with ZMUX_PACKET_ERROR.
	ErrMalformedPacket = errors.New("zmux: malformed packet stream")
)

Functions

func ALPNAlias added in v1.3.2

func ALPNAlias(id string) (string, bool)

ALPNAlias returns the draft-01 alias of a configured identifier, 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 AdmittedAs added in v1.4.5

func AdmittedAs[T any](a Admitted) (v T, ok bool)

AdmittedAs returns the Decision.Value of the admission that accepted a, as a T; ok is false when there is none or it is not a T. For a *Conn it is the value of the session's bootstrap carrier (for a split bootstrap, its uplink half's), which does not change for the session's lifetime, resumes included; for a *Pipe it is that of the pipe's carrier, the one that carried its Hello (the session's for the bootstrap pipe), and there is none once the session no longer knows the pipe. There is none on the dialing side. zmux does not compare a pipe's value with the session's: a host that requires a join to come from the session's client compares them, in WrapPipe or after the pipe event.

func BoundTLS added in v1.4.7

func BoundTLS(st tls.ConnectionState) bool

BoundTLS reports whether a completed TLS handshake can carry the Bound contract (CarrierSecure): TLS 1.3, or TLS 1.2 that did not resume. A missing extended master secret fails the export.

func EarlyRequest added in v1.4.5

func EarlyRequest(r *http.Request) bool

EarlyRequest reports whether r may have been received in TLS early data: an intermediary forwarded it from early data (Early-Data: 1, RFC 8470), or the server read it on a connection whose handshake has not completed, as an HTTP/3 server listening for 0-RTT does. Such a request is no carrier; AdmitUpgrade and AdmitRequest answer it 425.

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 IsCarrierSecure added in v1.4.0

func IsCarrierSecure(p PipeIO) bool

IsCarrierSecure reports the Secure declaration of a carrier; a split carrier needs it on both halves.

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 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 PresentPipe added in v1.3.2

func PresentPipe(ctx context.Context, p PipeIO, c CarrierCredential) 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 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.

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 {
	// 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
	// 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
	// FallbackOnPeekTimeout makes a byte-stream carrier whose prefix does
	// not arrive within PeekTimeout, in the first read or in a
	// VerdictMore round, take VerdictFallback with every byte read so far
	// replayed (without a fallback target it is stalled, as for any
	// fallback). It needs a receiving half that continues after its read
	// deadline passed (a net.Conn, a TLS connection); a carrier that does
	// not, a message-framed one and an HTTP request carrier are closed on
	// the timeout as when it is false. A Decide that does not return in
	// time is VerdictClose, and a failed outer handshake is not affected.
	FallbackOnPeekTimeout bool
	// 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 (admit.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. A carrier that Admission.FallbackOnPeekTimeout
	// takes to fallback is counted both here and in Fallback: the two
	// overlap for it.
	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, 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, except that a carrier Admission.FallbackOnPeekTimeout takes to fallback is counted in both PeekTimedOut and Fallback. All are zero without an Admission.

type AdmissionVerdict added in v1.4.5

type AdmissionVerdict uint8

AdmissionVerdict is the outcome of an admission.

const (
	// VerdictAccept hands the carrier to the Listener, without the first
	// Decision.Skip bytes of the prefix.
	VerdictAccept AdmissionVerdict = iota
	// VerdictFallback hands the carrier, with every byte read replayed, to
	// the fallback target of its kind (ListenerConfig.Fallback for byte
	// streams, zmuxhttp.Options.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
)

type Admitted added in v1.4.5

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

Admitted is a session or one of its pipes, whose admission value AdmittedAs reads: a *Conn or a *Pipe.

type AllowRecordMode added in v1.4.0

type AllowRecordMode func(c RecordPolicyInput, m RecordMode, peer any) bool

AllowRecordMode is the acceptor's check of a Hello's mode; peer is the session's host value (AdmittedAs).

type ApplicationError

type ApplicationError struct {
	ErrorMessage string
	ErrorCode    ApplicationErrorCode
	Remote       bool
}

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) and a slot of the listener (MaxPending) from its arrival, before any handshake, through the admission and until the carrier enters a session, is closed or is handed to a fallback. 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) DecideRequest added in v1.4.5

func (a *Arrival) DecideRequest(w http.ResponseWriter, r *http.Request, fallback http.Handler) bool

DecideRequest runs the admission of the arrival of r, a request taken as a carrier on its head (see AdmitUpgrade), for a host that checks the request between Listener.Arrive and the decision. On VerdictFallback it serves r with fallback (nil: http.NotFound); on VerdictStall and VerdictClose it aborts the request with http.ErrAbortHandler. It returns true on VerdictAccept, or without an Admission.

func (*Arrival) HandlePipe added in v1.3.2

func (a *Arrival) HandlePipe(ctx context.Context, p PipeIO, hint PipeHint) 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 slots when no carrier of it is handed on (the connection ended first). It may be called more than once, also after HandlePipe.

func (*Arrival) Take added in v1.4.5

func (a *Arrival) Take(ctx context.Context, p PipeIO, hint PipeHint) (run func(context.Context) error, err error)

Take hands p, a carrier of the arrival that its admission accepted (Admitted), to the listener, or refuses it at once, before it waits for anything: the listener is closed, it is shutting down and p is a split half, or the source has no slot for a further carrier. p takes the arrival's slots, as with HandlePipe, and is closed when refused. run does the rest of HandlePipe: it blocks for the lifetime of the pipe. Take serves an adapter that answers a carrier's request according to whether the listener took it (the exchange carrier); HandlePipe is Take and run in one.

type Backoff added in v1.4.6

type Backoff struct {
	// Min is the first wait. Zero: the user's default.
	Min time.Duration
	// Max is the longest wait. Zero: the user's default.
	Max time.Duration
	// Jitter is the largest fraction a wait is reduced by, in [0, 1).
	// Zero: the user's default; a negative value: none.
	Jitter float64
}

Backoff is a retry backoff: after a failed attempt the wait starts at Min and doubles up to Max, each wait reduced by a random fraction of up to Jitter. A zero field takes the default of the user of the Backoff (WithDefaults): for a redial source (Config.RedialBackoff, PipePool.Backoff, where the wait counts from the start of the previous attempt) DefaultMinBackoff, DefaultMaxBackoff and DefaultBackoffJitter; another user, such as a carrier, documents its own. A negative Min or Max, a Min above Max (the defaults filled in) or a Jitter of 1 or more (or NaN) is invalid (ErrInvalidConfig); a negative Jitter is a jitter of 0.

func (Backoff) WithDefaults added in v1.4.6

func (b Backoff) WithDefaults(def Backoff) (Backoff, error)

WithDefaults returns b with the fields of def in place of its zero fields and a negative Jitter as 0, or an ErrInvalidConfig error when b is invalid (see Backoff). def is taken as valid.

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. carrier.WriteFlat implements WriteBuffers over a single Write.

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 CarrierCredential) (PipeIO, error)
	// Target, for a kind dialed at a URL, is where its carriers start and
	// what redirects led them to (nil: not known). DialChoice keeps it per
	// server in CarrierChoicePolicy.Cache, and starts it at the base URL again
	// after a failure.
	Target CarrierTarget
	// Variant labels a transform the candidate's carriers run (PipeIO.Variant,
	// which DialChoice sets on what Dial returns when it is not ""). A kind
	// with different variants makes different candidates, each with its
	// own CarrierCache entry; DialChoice orders them as for different kinds,
	// so that the host states its preference by their order.
	Variant string

	// Join joins carriers of the kind to c, for a kind whose Dial does
	// not open a carrier that can join (a split bootstrap); nil: AddPipe
	// on a carrier from Dial. ctx bounds the attempt, life the carriers.
	Join func(ctx, life context.Context, c *Conn, cred CarrierCredential, o PipeOptions) ([]*Pipe, error)
}

Candidate is one carrier kind that DialChoice may use. Dial opens a carrier of the kind, presenting cred (the session's Config.CarrierCredential) for the server's admission; DialChoice 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.

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 {
	// Err is the failure (nil when usable).
	Err     error
	Variant string // the candidate's Variant
	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      uint64
	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 {
	// BackoffMin and BackoffMax bound the backoff of a failed kind (1 min,
	// 6 h).
	BackoffMin, BackoffMax time.Duration
	// SuccessTTL is how long a usable kind is remembered (6 h).
	SuccessTTL time.Duration
	// contains filtered or unexported fields
}

CarrierCache remembers which carrier kinds worked per server and local network (CarrierChoicePolicy.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 (CarrierChoicePolicy.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 DialChoice for the candidate of kind and variant under key (the CarrierChoicePolicy.Key in use), in the entry DialChoice'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 CarrierChoice added in v1.4.5

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

CarrierChoice is how DialChoice, or a PipePool, chooses the carrier: ExplicitChoice or AutoChoice.

func AutoChoice added in v1.4.5

func AutoChoice(c ...Candidate) CarrierChoice

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

func ExplicitChoice added in v1.4.5

func ExplicitChoice(c Candidate) CarrierChoice

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

type CarrierChoiceError added in v1.4.5

type CarrierChoiceError struct {
	Results []CandidateResult
}

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

func (*CarrierChoiceError) Error added in v1.4.5

func (e *CarrierChoiceError) Error() string

func (*CarrierChoiceError) Unwrap added in v1.4.5

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

Unwrap returns the candidates' errors.

type CarrierChoicePolicy added in v1.4.5

type CarrierChoicePolicy 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
	// Join establishes a session on the most robust candidate and joins
	// the preferred ones. It is on by default; with SwitchOff the
	// candidates are tried one after another, in order.
	Join Switch
}

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

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 CarrierCredential added in v1.4.5

type CarrierCredential 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)
}

CarrierCredential 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: Peer is the server's address and TLS the carrier's completed handshake (nil without TLS); Head is set for Header. admit.PrefixAuth is a CarrierCredential.

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

type CarrierInfo added in v1.3.2

type CarrierInfo struct {
	// 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
	// Source is the carrier's client address: what a trusted intermediary
	// reports (TrustedProxies; port 0 when it reports none), what the
	// host gave as PipeHint.Source, and otherwise Peer. The listener's
	// per-source limits and the stall duration count it aggregated to
	// its source prefix (ListenerConfig.SourcePrefixV4, SourcePrefixV6),
	// 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
	// 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 (CarrierCredential). 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
	// CarrierStream is a bidirectional streaming request: one request
	// whose body is the uplink and whose response body the downlink
	// (zmuxhttp.Streaming.Candidate).
	CarrierStream
	// CarrierSplit is a split bootstrap: an uplink POST and a downlink GET
	// (zmuxhttp.Split.Candidate).
	CarrierSplit
	// CarrierExchange is the exchange carrier of bounded requests
	// (zmuxhttp.Exchange.Candidate).
	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 CarrierPeer added in v1.4.0

type CarrierPeer interface{ CarrierPeer() any }

CarrierPeer is implemented by the halves of a carrier transform that authenticated the peer: its value is the session's host value in place of Decision.Value (AdmittedAs).

type CarrierRecordLimit added in v1.4.0

type CarrierRecordLimit interface{ MaxRecord() int }

CarrierRecordLimit is implemented by a carrier half that bounds a record's plaintext. It is local and applied beside the peer's max_record_size.

type CarrierRecordMode added in v1.4.0

type CarrierRecordMode interface{ RecordMode() RecordMode }

CarrierRecordMode is implemented by the halves of a carrier transform that ran an Establish: the first pipe is then on the secure carrier with this mode, and the session's secret comes from the half's exporter.

type CarrierSecure added in v1.4.0

type CarrierSecure interface{ CarrierSecure() bool }

CarrierSecure is implemented by a carrier half whose carrier meets the Bound contract (the carrier protects the records end to end: confidentiality and integrity). An exporter alone is no such declaration.

type CarrierTaker added in v1.4.5

type CarrierTaker interface{ CarrierTaken() }

CarrierTaker is a carrier's receiving half that records what the listener reads until the listener takes the carrier, so that a carrier it does not take can be handed on with those bytes replayed (at most MaxUntakenRead of them). The listener calls CarrierTaken once a session, a join or a lane attaches the carrier.

type CarrierTarget added in v1.4.5

type CarrierTarget interface {
	// URL is where the next carrier starts.
	URL() string
	// Base is the URL the target was made with.
	Base() string
	// Redirected moves the target to url, a URL redirects led to.
	Redirected(url string)
	// Reset starts the target at its base URL again.
	Reset()
}

CarrierTarget is where the carriers of a kind dialed at a URL start, and what redirects led them to; zmuxhttp.Target is one. CarrierCache remembers the URL a usable kind's redirects found and starts the target there in later dials.

type Change added in v1.4.5

type Change[T any] struct {
	// contains filtered or unexported fields
}

Change is one field of a PipeUpdate, in one of three states: the zero value keeps the setting, Set(v) sets it to v and Clear returns it to its default.

func Clear added in v1.4.5

func Clear[T any]() Change[T]

Clear returns a Change that returns a setting to its default.

func Set added in v1.4.5

func Set[T any](v T) Change[T]

Set returns a Change that sets a setting to v.

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 CloseCodeRecorder added in v1.4.5

type CloseCodeRecorder interface {
	RecordCloseCode(code ApplicationErrorCode, reason string)
}

CloseCodeRecorder is a half whose carrier connection outlives its pipes and ends with an application error code of its own, such as a QUIC connection: when the session ends, zmux passes its close code and reason to each pipe's halves before it ends them: those of its application close (CONNECTION_CLOSE 0x1d, sent or received), or 0 and an empty reason after any other end (a transport error, an idle timeout), so that the adapter closes the connection, once no pipe uses it, with the code of the last session it carried. It may be called more than once with the same code; a pipe removed while its session runs passes nothing. A transform may forward it.

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: the peer's transport
	// parameters must arrive within it. Zero is 10 s; a negative value is
	// no timeout. It does not bound joins (JoinTimeout).
	HandshakeTimeout time.Duration
	// JoinTimeout is the deadline of every join: a pipe this endpoint adds
	// (AddPipe without a context deadline, Redial, PipePool), a pipe or
	// lane the peer adds until it is confirmed, a join held for the join
	// keys and a carrier stalled after a rejected join. Zero is
	// DefaultJoinTimeout (10 s); it cannot be no timeout, so a negative
	// value is invalid, and so is one above the maximum join deadline of 60 s,
	// on which epoch retention rests. It is independent of HandshakeTimeout.
	JoinTimeout time.Duration
	// EpochPeriod, EpochJoins, EpochAfterFirstPipe and EpochAfterResume
	// are the policy of session epochs, the key exchanges that evolve the
	// session secret. A multipath session advances its epoch after EpochPeriod
	// in one epoch, after EpochJoins joins in it, once when its first Sealed or
	// Bound pipe exists if its secret comes from a TLS exporter or a pre-shared
	// key (EpochAfterFirstPipe), and once after a suspension ends
	// (EpochAfterResume). Zero EpochPeriod and EpochJoins are the defaults,
	// every hour and every 65536 joins; a negative one turns that trigger
	// off. The two switches are on by default; SwitchOff turns theirs off.
	EpochPeriod         time.Duration
	EpochJoins          int
	EpochAfterFirstPipe Switch
	EpochAfterResume    Switch
	// EnableDatagrams announces max_datagram_frame_size and datagram flows.
	EnableDatagrams bool
	// ShapingPreciseTimer meets shaping deadlines in place: the session's
	// timer is armed ahead by the host timer's observed lateness, at most
	// 2 ms, and its callback yields in a loop until the deadline, which costs
	// CPU time up to that lead on one goroutine per deadline. Off: deadlines
	// are met as the host timer allows.
	ShapingPreciseTimer bool
	// 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
	// Liveness are the keep-alive, failure detection and probe settings
	// of the session and the defaults of its pipes; Conn.SetLiveness
	// replaces them while the session runs.
	Liveness Liveness

	// InitialStreamReceiveWindow is the initial receive window of a
	// stream, in bytes. Zero is 256 KiB; otherwise at least 4 KiB; a
	// negative value is invalid.
	InitialStreamReceiveWindow int64
	// MaxStreamReceiveWindow caps the auto-tuning of a stream's window, in
	// bytes. Zero is automatic: a 64 MiB floor that grows within the memory
	// budget; a negative value is invalid.
	MaxStreamReceiveWindow int64
	// 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, in
	// bytes. Zero is 1 MiB; otherwise at least 16 KiB; a negative value is
	// invalid.
	InitialConnectionReceiveWindow int64
	// MaxConnectionReceiveWindow caps the session window, in bytes. Zero
	// is automatic: a 96 MiB floor; a negative value is invalid.
	MaxConnectionReceiveWindow int64
	// MemoryBudget bounds the memory of a session without a listener, in
	// bytes. Zero is 1 GiB; a negative value is unlimited.
	MemoryBudget int64

	// MaxIncomingStreams is initial_max_streams_bidi, the bidirectional
	// streams the peer may open at first. Zero is 256; a negative value
	// grants none; otherwise at least 4 and at most MaxStreamCredit.
	MaxIncomingStreams int64
	// MaxIncomingUniStreams is initial_max_streams_uni. Zero is a staged
	// credit: 16, raised to 256 on the first AcceptUniStream; a negative
	// value grants none; otherwise at most MaxStreamCredit.
	MaxIncomingUniStreams int64

	// 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. DatagramReceiveBytes bounds the session
	// queue and the datagrams held for streams not opened yet, not the
	// stream queues.
	DatagramSendQueue    int
	DatagramReceiveQueue int
	DatagramStreamQueue  int
	DatagramReceiveBytes int64
	// DatagramStreamBytes bounds the payload bytes of each stream's
	// datagram queue, per direction of receipt, beside DatagramStreamQueue:
	// a datagram that would exceed either drops the oldest of that queue
	// until both hold, each counted as dropped; a single datagram larger
	// than it is kept alone. Zero is 512 KiB; a negative value is
	// unlimited, leaving the count as the only bound. DatagramReceiveBytes
	// does not include the stream queues, so with the defaults a session's
	// received datagrams are bounded by about MaxIncomingStreams x
	// DatagramStreamBytes (256 x 512 KiB) beside it.
	DatagramStreamBytes int64

	// SendBuffer starts the written-but-unreleased byte budget, in bytes.
	// Zero is 4 MiB; a negative value is invalid. Multipath sessions grow
	// it to the retransmit budget, within MaxSendBuffer.
	SendBuffer int64
	// MaxSendBuffer fixes its growth maximum, in bytes; one below
	// SendBuffer (or its default), or a negative one, is invalid. Zero is
	// automatic: a 64 MiB floor, above it within the memory budget.
	MaxSendBuffer int64

	// 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, the join replay window. Zero is
	// max(64, 2*(MaxPipes+H)); a window below MaxPipes+H is invalid.
	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, at least 1 ms
	// (a fraction of a millisecond is rounded up). Zero is no resume; a
	// negative value is invalid. Resume needs a secret source (PipeAuth),
	// and a server session a Listener; a client should have a redial
	// source (Redial or MaintainPipes).
	ResumeTimeout time.Duration

	// Scheduler is the session's scheduling policy (nil: SchedulerAffinity).
	Scheduler Scheduler
	// SchedulerParams tune the scheduler and failure detection.
	SchedulerParams SchedulerParams
	// ShapingLimits are the application's bounds on shaping; an account field
	// above its maximum is invalid.
	ShapingLimits shaping.Limits
	// ShapingBudget gives the shaping configuration's budget, called once per
	// session outside every lock; nil: none. It cannot widen ShapingLimits.
	ShapingBudget func() shaping.Budget
	// HandshakeShaper is asked for the plan of each Join message this session
	// writes; nil: none.
	HandshakeShaper shaping.HandshakeShaper
	// 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 configures the source of the session secret. Multipath
	// (MaxPipes above 1) and resume need one: a PSK, a deferred PSK or the
	// exporter; on a secure first pipe the secure carrier is the source and
	// PipeAuth sets none of them. Without a source Start fails with
	// ErrInvalidConfig before a byte is written. A source is never dropped
	// because the peer did not offer it: flags that differ close the
	// session.
	PipeAuth PipeAuth
	// RecordPolicy chooses the record mode of each carrier this endpoint joins; nil is
	// always Sealed. PipeOptions.RecordMode wins over it.
	RecordPolicy RecordPolicy
	// AllowRecordMode is the acceptor's check of a Hello's mode; nil passes only Sealed.
	AllowRecordMode AllowRecordMode
	// AuthorizeJoin is an acceptor's further check of a join; nil passes all.
	AuthorizeJoin func(c *Conn, pipe PipeID) bool
	// JoinEarlyHello is the size of a Hello's first batch in bytes: 0 takes
	// 8 KiB; a negative value sends no first batch. Larger batches outgrow
	// the first congestion window and delay both the Hello and the Reply.
	JoinEarlyHello int

	// EarlyData enables early data: stream data before the peer's
	// transport parameters arrive.
	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
	// Logger receives what the application would otherwise not see: a
	// warning when the last pipe of a direction is removed while streams
	// are open, a warning with EventResumeUnattended, and the failures of
	// host callbacks that zmux contains (a panic in a hook). It is called
	// outside every lock and must not block; nil logs nothing. What the
	// events and the Tracer report is not logged again.
	Logger *slog.Logger
	// CarrierCredential 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).
	CarrierCredential CarrierCredential
	// Redial re-establishes pipes after failures (resume): it is called
	// as soon as the session lacks a direction or suspends, delayed only
	// by the redial backoff since its previous call for that direction,
	// and by the join refusal backoff a refused join started (the longer
	// of the two). 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)
	// RedialBackoff is the backoff of Redial: after a failed call the wait,
	// counted from the start of the previous call, starts at Min and
	// doubles up to Max, each wait reduced by a random fraction of up to
	// Jitter. The zero value is the default (1 s, 60 s, 0.2). The pools of
	// MaintainPipes follow the same rule with state of their own
	// (PipePool.Backoff).
	RedialBackoff Backoff
	// RedialPolicy, when set, is asked before each Redial call; DialAfter
	// is the wait from the previous call to the next (at most
	// RedialBackoff.Max; 0: the backoff), and Liveness applies 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 value is the off, none, no timeout or unlimited setting where the field says so and invalid (ErrInvalidConfig) otherwise, and a Switch turns off a feature that is on by default. A value out of range is an error, never corrected.

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.CarrierCredential, the connection starts with its prefix (PresentPipe; a *tls.Conn is handshaken first). zmux owns c from then on, whether Client succeeds or fails (as Start).

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 zmux owns from then on, whether the session starts or not. It returns as Start does; ctx bounds the dial and establishment, not the session.

func DialChoice added in v1.4.5

func DialChoice(ctx context.Context, m CarrierChoice, cfg *Config, pol *CarrierChoicePolicy) (*Conn, error)

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

ExplicitChoice dials its one candidate as its own dialer does. AutoChoice 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 CarrierChoicePolicy.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, Join off, 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 *CarrierChoiceError.

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 zmux owns from then on. ctx bounds the dial and both handshakes, not the session.

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, err := zmux.NewListener(nil)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer func() { _ = l.Close() }()
	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 and ResumeTimeout with ErrInvalidConfig. zmux owns c from then on, whether Server succeeds or fails (as Start).

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.

The carrier belongs to zmux from the call on, whether Start succeeds or fails: on any error, ErrInvalidConfig included, its halves are closed before Start returns, and the caller does not close them. ctx bounds establishment only; the session's lifetime is Conn.Context, which does not inherit ctx.

A session in the server or auto role started here has no Listener, so it cannot take joins: MaxPipes above 1 or ResumeTimeout is ErrInvalidConfig (serve such sessions with a Listener).

func (*Conn) Abort

func (c *Conn) Abort(code ApplicationErrorCode, reason string)

Abort ends the session at once with an application error: it sends CONNECTION_CLOSE with code and reason on each usable outbound pipe whose carrier takes it, discards the data not yet sent, fails the open streams with the session's error and returns without waiting for any carrier. The carriers are then shut down gracefully in the background, as CloseWithError does after its hand-off. Code 0 is allowed and differs from Close only in what is drained. An Abort after CloseWithError or Abort sends nothing more, except that one while CloseWithError is still flushing ends the flush, sending the close's code and reason.

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) Adapter added in v1.4.6

func (c *Conn) Adapter() *ConnAdapter

Adapter returns c's view for carrier adapters.

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 with the Join handshake and returns once the peer has attached the pipe (Pipe.WaitAttached), or with PipeOptions.ReturnOnReply once the Reply has been verified. ctx bounds the call, and otherwise Config.JoinTimeout. The carrier belongs to zmux from the call on: when AddPipe fails, ErrInvalidConfig included, it has been closed. A refusal returns ErrJoinRefused and starts the backoff. A join that the attachment cap or the refusal backoff holds waits for room. A pipe that the peer has not attached when ctx or the timeout ends is aborted, and ctx's error returned; one that fails or goes first returns ErrPipeGone. A send-only pipe is attached by an acknowledgement, which the peer sends on an inbound direction: without another pipe that receives, the default wait lasts until the deadline. In Bound, a carrier whose handshake (a *tls.Conn half, or a Handshaker) has not completed is first driven through it with ctx; a failed handshake closes it. On a session that returned before establishment (EarlyData), AddPipe first waits for it.

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"), EndToEnd: true}}
l, err := zmux.NewListener(&zmux.ListenerConfig{Config: cfg})
if err != nil {
	fmt.Println(err)
	return
}
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.PipeHint{}) }()
go func() { _ = l.HandlePipe(ctx, zmux.NetPipe(b1), zmux.PipeHint{}) }()

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: zmux.Set(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.PipeID == 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) AdvanceEpoch added in v1.4.0

func (c *Conn) AdvanceEpoch() error

AdvanceEpoch starts a session epoch exchange at once when the session is Stable, or right after the one in progress. The exchange is reported by EventEpochCommitted and EventEpochDeleted. It fails with ErrNotNegotiated when multipath is not in use and with ErrJoinPending before the session has its join keys.

func (*Conn) Close

func (c *Conn) Close() error

Close is CloseWithError(0, ""): the graceful close without error. It always returns nil, and makes Conn an io.Closer.

func (*Conn) CloseWithError added in v1.0.4

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

CloseWithError closes the session gracefully with an application error code and reason, which the peer sees as ApplicationError (code 0 and an empty reason is the close without error). The data the streams have written and not yet sent is sent first, as far as flow control and the carriers allow; then CONNECTION_CLOSE is handed to the carrier of every usable outbound pipe, after which each pipe's write side is shut down gracefully and its inbound side read until the peer ends it or the linger timeout passes. Streams still open fail with the session's error; they are not waited for (Shutdown waits for them). CloseWithError returns once CONNECTION_CLOSE has been handed to every such carrier (written to it; for a socket, taken into the kernel's send buffer), at once when no pipe can carry it, and at the latest one second after the call, flushing included: what has not been handed over by then is discarded and the carriers that did not take CONNECTION_CLOSE are closed. The half-close and the linger go on in the background, so a process may exit as soon as it returns; Wait and Done wait for them, and so for the peer to have read the close.

CloseWithError (and Close) and Abort are idempotent: the first call of either decides the code, the reason and what is sent, and a later call returns no later than the first and sends nothing more, except that an Abort while CloseWithError is still flushing discards what remains unsent and ends the flush at once, still with the close's code and reason. Either returns at once on an ended session. CloseWithError always returns nil.

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. It does not inherit the context passed to Start, Client or Dial, which bounds establishment only.

func (*Conn) DeclareEndToEnd added in v1.4.0

func (c *Conn) DeclareEndToEnd()

DeclareEndToEnd states that the host has proven pipe 0 end to end, for example with a pinned certificate or an attestation over an exporter of its own label. It is local and sends nothing. Until then a session whose first pipe is not on the secure carrier has no join keys: local joins fail with ErrJoinPending and the peer's are held. The library stops a host from forgetting or joining too early, not from declaring falsely. A session on a secure first pipe needs no call, and one is a no-op.

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) Done added in v1.4.5

func (c *Conn) Done() <-chan struct{}

Done returns a channel that is closed when Wait would return; Wait then returns the session's error at once. A select on it bounds the wait with a timer or a context, "the close delivered or given up after d":

_ = conn.CloseWithError(code, "replaced")
select {
case <-conn.Done():
case <-ctx.Done(): // the linger goes on and ends the carriers
}

A wait given up this way changes nothing in the session.

func (*Conn) Epoch added in v1.4.0

func (c *Conn) Epoch() uint64

Epoch is the epoch new local joins use.

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. A value that binds a channel to the session takes at least 32 bytes and a label of its own: shorter ones can collide and identify nothing.

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 included), 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, o *PipeStreamOptions) (PipeIO, error)

OpenPipeStream opens a stream of c to carry a pipe pair of another session, with the preamble o (nil: PIPE_CARRIER only). Nothing is sent before the nested session writes its first record. When the peer does not use the preamble, o must be empty.

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 PipeID) (*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: 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 MaxStreamCredit 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) ReplacePipes added in v1.4.5

func (c *Conn) ReplacePipes(ctx context.Context) error

ReplacePipes advances the epoch as AdvanceEpoch does, waits until new joins use the new epoch, and then replaces every pipe the session had when it was called: for each, it dials a carrier of the same direction through Config.Redial, joins it, and closes the old pipe gracefully once the new one is attached (make before break). It serves only a suspected leak of a session-level secret; ordinary rotation is AdvanceEpoch or the epoch policy. Without Config.Redial it is ErrInvalidConfig.

ctx bounds the whole call: when it ends, the call fails with ctx's error, the pipes already replaced stay replaced and the old pipes not yet replaced are kept. A dial or join that fails ends the call with its error on the same terms. While the previous epoch is still kept, the next offer waits until it is deleted, so a ctx shorter than that wait fails the call before any pipe is replaced.

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. 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 (together with the exporter when both are configured) and the held joins of the peer go on. It fails with ErrInvalidConfig without DeferredPSK or with a shorter PSK, ErrNotNegotiated after an establishment without multipath, 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 Liveness: 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.Liveness, PipeUpdate.Liveness) 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 PipeID, 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, budget func() shaping.Budget)

SetShaper installs f on every outbound pipe of the session, replacing earlier instances; nil: no shaping. budget gives the configuration's budget, called once here outside the lock; nil replaces an earlier budget with none, so that only ShapingLimits apply. The account's spending carries over.

func (*Conn) SetShapingLimits added in v1.3.3

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

SetShapingLimits replaces the session's Config.ShapingLimits, tighter or looser; they are never sent. The account's spending carries over. 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) ShapingMeters added in v1.4.0

func (c *Conn) ShapingMeters() shaping.Meters

ShapingMeters returns the session's shaping readings.

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 the graceful close of Close, with code and 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 has wholly ended, then returns the session's error: until it is closed, every pipe's inbound side has ended (the peer read CONNECTION_CLOSE and ended its side of the carrier) or the linger timeout has expired, and every goroutine of the session has ended. After CloseWithError, a Wait that returns before the linger timeout confirms that the peer read the close. Done is its selectable form.

func (*Conn) WeakestRecordMode added in v1.4.0

func (c *Conn) WeakestRecordMode() RecordMode

WeakestRecordMode is the session's protection: that of its weakest pipe, Unmanaged included. A host can authorize by it.

type ConnAdapter added in v1.4.6

type ConnAdapter Conn

ConnAdapter is the view of a Conn for the author of a carrier adapter or of a pool: what only code that dials carriers for a session needs. Conn.Adapter returns it.

func (*ConnAdapter) JoinReady added in v1.4.6

func (a *ConnAdapter) JoinReady() bool

JoinReady reports whether the maintenance target and join admission permit dialing another pipe now: for a pool or an own redial loop, which dials only when it may. Explicit AddPipe still follows the physical cap.

type ConnectionState added in v1.3.0

type ConnectionState struct {
	Role        Role
	Established bool
	// Suspended: the session has no pipe and waits for one (resume).
	Suspended          bool
	SupportsDatagrams  struct{ Local, Remote bool }
	SupportsResetAt    struct{ Local, Remote bool }
	Multipath          bool
	PipeAck            bool
	Resume             bool
	JoinSecurityAbsent bool
	// JoinPending: there are no join keys yet, because Conn.SetJoinSecret has not
	// supplied the deferred PSK or an Unmanaged first pipe was not declared end to end.
	JoinPending bool
	// WeakestRecordMode is the mode of the session's weakest pipe.
	WeakestRecordMode RecordMode
	PeerIsZmux        bool
	// QMuxVersion is the QMux version in use (QMuxVersion, the only one).
	QMuxVersion string
	// ApplicationProtocol is the application protocol the bootstrap carrier
	// negotiated: PipeIO.Protocol (a WebSocket subprotocol, for example),
	// else, for a raw TLS or QUIC carrier, the ALPN of the handshake this
	// process ran for it; empty when neither gives one.
	ApplicationProtocol string
	// TLS is the state of the TLS (or QUIC) handshake this process ran for
	// the bootstrap carrier (TerminatedTLS); nil where TLS ended outside
	// the process or the carrier has none.
	TLS *tls.ConnectionState
	// 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 is the largest session datagram payload the peer
	// accepts now, 0 when it accepts none; Stream.MaxDatagramPayload gives
	// the one of a stream.
	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 (DialChoice), the
	// latest after a switch; 0 for a session not dialed in a mode. The
	// chosen candidate's Variant is its pipe's PipeStats.Variant.
	Carrier CarrierKind
	// 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: 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 // Hellos that did not verify
	JoinReplays      uint64 // joins closed as replays or too late
	// JoinPending counts peer joins held for the join keys (not join auth failures).
	JoinPending uint64
	// JoinFailures counts own consecutive failed joins, reset by a Proven join.
	JoinFailures uint64
	// JoinBatchDropped counts first batch frames dropped without closing the session.
	JoinBatchDropped 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. 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 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: 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 {
	// Value is the host's value for an accepted carrier (VerdictAccept
	// only; ignored otherwise): zmux hands it on without looking at it to
	// WrapPipe (PipeHint.Admitted) and to the session (AdmittedAs) or
	// pipe (AdmittedAs) 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
	// 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
	// Skip is the number of leading prefix bytes that are not carrier bytes
	// (VerdictAccept only); the rest is replayed to the Listener.
	Skip int
	// Need is, with VerdictMore, the total prefix length Decide needs.
	Need    int
	Verdict AdmissionVerdict
}

Decision is what Admission.Decide returns.

type Direction

type Direction uint8

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

const (
	DirectionBidirectional Direction = iota
	DirectionSendOnly
	DirectionReceiveOnly
)

type DuplicateOptions added in v1.3.0

type DuplicateOptions struct {
	Dial func(ctx context.Context) (PipeIO, error)
	// 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
}

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 duplicate-session rule 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.
	// What the pipe reads reaches the session only after the verdict has
	// been applied, so the verdict must not depend on the session; a read
	// half may itself deliver it, as long as it returns no bytes before.
	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; with
	// RoleAuto, where no side is the client, it is invalid).
	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. 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{MaxIncomingStreams: -1})
	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.

A carrier may add HandshakeFailed() <-chan struct{}, closed when the handshake can no longer complete: a reader waiting for it then ends at once rather than at Config.HandshakeTimeout.

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
	// Epoch of EventEpochCommitted and EventEpochDeleted.
	Epoch uint64
	// 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
	// PipeID is the pipe ID of a pipe event.
	PipeID PipeID
	// 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 uint64
	// 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                             []PipeID
}

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 (DirectionSendOnly) or the inbound one ended (DirectionReceiveOnly)
	// (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
	// EventResumeUnattended follows EventSessionSuspended when nothing in
	// the library will dial for the session: it can rejoin (the peer gave
	// a Session Locator) but has neither a Config.Redial hook nor a running
	// MaintainPipes pool, so it ends at its resume timeout unless the
	// application adds a pipe (no fields). It is also logged as a warning
	// (Config.Logger). An application that resumes with its own AddPipe
	// calls reacts to EventSessionSuspended and can ignore it.
	EventResumeUnattended
	// 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 DialChoice
	// (Carrier, Outcome).
	EventCarrierCandidate
	// EventCarrierChosen reports the carrier kind DialChoice 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
	// EventEpochCommitted reports that the session committed an epoch (Epoch):
	// its secret is known, and joins of it are accepted.
	EventEpochCommitted
	// EventEpochDeleted reports that an epoch (Epoch), its keys and its
	// Locators were deleted.
	EventEpochDeleted
)

func (EventKind) String added in v1.3.0

func (k EventKind) String() string

type Framing added in v1.3.0

type Framing uint8

Framing is a carrier's record framing.

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: 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 HandshakeTimeoutError added in v1.3.0

type HandshakeTimeoutError struct{}

HandshakeTimeoutError reports that the peer's transport parameters did not arrive within Config.HandshakeTimeout: the session was never established. It matches ErrHandshakeTimeout and net.ErrClosed.

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 and net.ErrClosed.

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 and net.ErrClosed: the session ended, which is not a timeout of the operation that observed it.

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 and net.ErrClosed.

type InboundState added in v1.3.2

type InboundState uint8

InboundState is the state of a pipe's inbound direction in its life cycle; 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 why a Hello failed verification.

func (JoinAuthReason) String added in v1.3.2

func (r JoinAuthReason) String() string

String returns the name the API specification uses ("auth", "kex", ...).

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 the Bound record mode 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 the Bound record mode. 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 (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 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, 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 zmuxhttp.NewHandler HTTP carriers. Accept returns the sessions it started:

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

A listener that took a carrier runs a goroutine until it is closed: call Close (or Shutdown) when done with it, as for a net.Listener. 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, error)

NewListener returns a listener; feed it carriers with Serve, HandlePipe or zmuxhttp.NewHandler, and Close it when done. cfg may be nil. It validates the whole configuration: an InstanceID longer than MaxInstanceIDLen, a negative count, a Config invalid for a server session, an invalid Admission or a WrapPipe whose Validate fails is ErrInvalidConfig.

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) Adapter added in v1.4.6

func (l *Listener) Adapter() *ListenerAdapter

Adapter returns l's view for carrier adapters. A nil l gives a nil view, on which CountSetupFailure does nothing.

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) HandlePipe added in v1.3.0

func (l *Listener) HandlePipe(ctx context.Context, p PipeIO, hint PipeHint) 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) 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) 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 ListenerAdapter added in v1.4.6

type ListenerAdapter Listener

ListenerAdapter is the view of a Listener for the author of a carrier adapter or of an own accept loop: arrival slots, HTTP upgrade admission, source stall durations, join lookups, memory charging, setup-failure counting, and the listener's internal timeouts and clock. Listener.Adapter returns it; the application-facing methods stay on the Listener. It has no state of its own and is safe for concurrent use as the Listener is.

func (*ListenerAdapter) AdmitRequest added in v1.4.6

func (a *ListenerAdapter) AdmitRequest(w http.ResponseWriter, r *http.Request, trusted *TrustedProxies, fallback http.Handler) (*Arrival, bool)

AdmitRequest is AdmitUpgrade for a request whose body is the carrier: the decision's prefix is the start of the body (none for a request without one, decided on its head), and on VerdictAccept r.Body continues after the skipped bytes. On VerdictFallback r.Body replays the bytes read.

func (*ListenerAdapter) AdmitUpgrade added in v1.4.6

func (a *ListenerAdapter) AdmitUpgrade(w http.ResponseWriter, r *http.Request, trusted *TrustedProxies, fallback http.Handler) (*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 trusted resolves (TrustedProxies.RequestSource). 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 (EarlyRequest). 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 fallback; nil: http.NotFound) or ended it (VerdictStall, VerdictClose, which abort the request with http.ErrAbortHandler), and the caller returns.

func (*ListenerAdapter) Arrive added in v1.4.6

func (a *ListenerAdapter) Arrive(source, peer netip.AddrPort) (*Arrival, error)

Arrive takes a slot of source and a slot of the listener for a carrier that arrived from peer (source zero: peer). When every slot of the listener is taken, the oldest stalled carrier is closed to make room; a source without a free slot or a closed listener (net.ErrClosed) refuses the carrier (ListenerStats.Refused), and so does a full listener with no stalled carrier (ListenerStats.Rejected): the caller closes the carrier without a handshake.

func (*ListenerAdapter) ChargeMemory added in v1.4.6

func (a *ListenerAdapter) ChargeMemory(delta int64)

ChargeMemory charges delta bytes (negative: gives them back) to the listener's memory budget, for data an adapter buffers outside a session; it is safe for concurrent use and does not block.

func (*ListenerAdapter) Clock added in v1.4.6

func (a *ListenerAdapter) Clock() timeshim.Clock

Clock is the listener's clock (Config.Clock, or the host's).

func (*ListenerAdapter) CountSetupFailure added in v1.4.6

func (a *ListenerAdapter) 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 (*ListenerAdapter) FirstRecordTimeout added in v1.4.6

func (a *ListenerAdapter) FirstRecordTimeout() time.Duration

FirstRecordTimeout is the effective ListenerConfig.FirstRecordTimeout, the bound an adapter applies to the start of a carrier it reads itself.

func (*ListenerAdapter) HandshakeTimeout added in v1.4.6

func (a *ListenerAdapter) HandshakeTimeout() time.Duration

HandshakeTimeout is the effective Config.HandshakeTimeout of the listener's sessions.

func (*ListenerAdapter) HasAdmission added in v1.4.6

func (a *ListenerAdapter) HasAdmission() bool

HasAdmission reports whether the listener runs an admission (ListenerConfig.Admission): an adapter that answered a carrier's request only once the listener took the carrier answers an admitted one at once.

func (*ListenerAdapter) KnownJoin added in v1.4.6

func (a *ListenerAdapter) KnownJoin(prefix []byte) (known bool, need int)

KnownJoin reports, for use in Admission.Decide, whether prefix begins a Join Hello (the first byte of a join) whose Locator names a session of l at this moment. A prefix that is not a Join, or is malformed (a suite this process does not have, reserved mode bits, a zero Locator length), gives false, 0. When prefix ends before the Locator and the nonce that follows it (the head of the Hello), need is the total prefix length required, to return as Decision.Need with VerdictMore; Admission.MaxPeek must allow it: at most 259 bytes plus the suite's nonce length (32 for the suites defined), 291 in all. On a message-framed carrier the prefix is the whole message and need > 0 means it is too short.

The answer is advisory: the join still authenticates, and a session that ended meanwhile gets OnReject as for any unknown Locator. l.mu is held for the lookup only.

func (*ListenerAdapter) MemoryPressure added in v1.4.6

func (a *ListenerAdapter) MemoryPressure() bool

MemoryPressure reports whether the memory charged to the listener's budget is above ListenerConfig.MemoryBudget: an adapter that buffers a carrier's data outside a session (the exchange carrier) then takes no more.

func (*ListenerAdapter) MemoryUsed added in v1.4.6

func (a *ListenerAdapter) MemoryUsed() int64

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

func (*ListenerAdapter) StallDuration added in v1.4.6

func (a *ListenerAdapter) 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.

type ListenerConfig added in v1.3.0

type ListenerConfig struct {
	// Config is the configuration of the sessions it accepts, validated by
	// NewListener as a server session's. 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;
	// its JoinTimeout bounds a stalled join.
	Config *Config
	// Logger receives the listener's warnings and the panics of its host
	// callbacks that it contains (OnReject, SessionConfig, Admission) and
	// the errors SessionConfig returns;
	// nil logs nothing. The sessions log to their Config.Logger.
	Logger *slog.Logger
	// 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 before they belong to
	// a session: a carrier holds one of its slots from its arrival, through
	// its handshake, the admission, the inbound transform, a split half's
	// wait for its partner, the classification, join verification and the
	// exchange of transport parameters, and through a stall, until it
	// enters a session, is closed or is handed to a fallback. Zero is 1024;
	// a negative value is unlimited. When every slot is taken, a new
	// carrier closes the oldest stalled carrier to take its slot, or, with
	// none stalled, is closed at once (ListenerStats.Rejected). Stalled
	// carriers hold at most half of MaxPending; a carrier to be stalled
	// beyond that is closed (AdmissionStats.StallOverflow).
	MaxPending int
	// MaxPendingPerSource bounds those carriers per source (zero: 8),
	// stalled ones included: a new carrier beyond it is refused, and a
	// source holds at most MaxPendingPerSource - 1 stalled carriers, a
	// carrier to be stalled beyond that being closed. A source is a client
	// address aggregated to its source prefix (SourcePrefixV4,
	// SourcePrefixV6); deployments behind a carrier-grade NAT raise it.
	// Each half of a split bootstrap holds a slot until the pair is
	// complete, so split bootstraps need at least 2.
	MaxPendingPerSource int
	// SourcePrefixV4 and SourcePrefixV6 aggregate a source to its prefix:
	// an IPv4 source (an IPv4-mapped IPv6 one included) counts by its first
	// SourcePrefixV4 bits (1 to 32; zero: 32, the address on its own), an
	// IPv6 source by its first SourcePrefixV6 bits (1 to 128; zero: 64),
	// ports ignored. This one aggregation is used by everything the
	// listener keeps per source: the MaxPendingPerSource slots, the count of
	// a source's stalled carriers and the stall duration
	// (Listener.StallDuration). A shorter prefix groups more clients into
	// one share, which tightens the bound against one network and lets its
	// clients crowd each other out; the defaults suit public listeners. A
	// negative value or one beyond the address length makes NewListener
	// fail with ErrInvalidConfig; there is no off setting.
	SourcePrefixV4, SourcePrefixV6 int
	// MaxPendingPerSession bounds the Unconfirmed carriers of one session:
	// joins that passed authentication and wait for the joiner's
	// confirmation. Zero is 4; a new authenticated Hello beyond it evicts
	// the one that has been Unconfirmed longest and is never refused for
	// lack of room.
	MaxPendingPerSession 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 with CONNECTION_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
	// OnReject decides the response to an unauthenticated carrier, the one
	// response to every refusal before authentication: a carrier beyond the
	// pending limits ("pending_limit", Profile 0), an unknown Locator, a
	// Suite outside the implementation or the session's set ("unknown_suite"),
	// a failed Hello, a join that memory pressure refuses ("memory_pressure"),
	// or an Establish a transform refused (RejectError). Every such refusal
	// gets the same response content and way of ending (no byte, a close or a
	// stall of the same bound); processing time is not covered. Without it,
	// a transform's rejection before authentication (an unknown Handle, a
	// wrong pre-shared key, a Profile or mode not accepted) and a carrier
	// beyond the pending limits are stalled, and a join's is closed. A stalled
	// carrier gets no byte and holds a stall slot of its source; when the
	// source's slots are full it is closed at once, whatever the reason. A
	// stalled join ends at Config's join timeout counted from the
	// rejection, whether or not it named a session; a stalled Establish at
	// Config's handshake timeout, at most the listener's stall bound
	// (Admission.StallMax; without one, drawn as Admission draws it). No verdict sends anything. An acceptor
	// that closes at once keeps at least 8 random bytes after InstanceID in
	// every locator, which NewListener guarantees.
	OnReject func(RejectInfo) RejectAction
	// MemoryBudget bounds the sum over the listener's sessions of buffered
	// receive data, retained data and session window growth. Zero is
	// 1 GiB; a negative value 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
	// fails 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 (once
	// they are read, WriteTo and ReadFrom use the carrier's own, and Unwrap
	// returns it); nil: they are stalled. It returns when it is done
	// with c, and closes it. HTTP carriers fall back to zmuxhttp.Options.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; a function is a WrapPipeFunc. A
	// PipeWrapper that also has a Validate() error method, such as a
	// secure-carrier server configuration, is validated by NewListener. Split carriers are wrapped once, after pairing,
	// as one p.
	//
	// While it runs the carrier holds its slots (MaxPending,
	// MaxPendingPerSource), and Config.HandshakeTimeout bounds it: ctx
	// ends at that bound, 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 PipeWrapper
	// 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; an
	// error and a panic are logged (Logger).
	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 a negative MemoryBudget unlimited; any other negative value makes NewListener fail with ErrInvalidConfig.

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 reason on the wire:
	// 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. 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 sends a QX_PING when the session has had no activity
	// this long. Zero is 15 s (DefaultKeepAlivePeriod); a negative value
	// turns keep-alive off; otherwise 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 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
	// 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 how long a suspect pipe stays suspect before it
	// fails. Zero is derived from the RTT and the idle timeout; otherwise
	// at least 1 s.
	DeadTimeout time.Duration
	// StandbyProbe is the probe interval of standby pipes and of pipes of
	// a less-preferred tier while the session carries traffic. Zero is
	// 1 s; a negative value turns these probes off (such pipes are then
	// probed at ProbeInterval); 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, which leaves the PIPE_PING of an answer, the standby
	// probes and the probes of pipes without an outbound direction at the
	// peer; otherwise at least 1 s.
	ProbeInterval time.Duration
	// ProbeJitter is the probe jitter j, below 1: each probe waits a
	// uniform draw from [k x (1 - j), k], the first one of pipe 0 from
	// [0, k]. Zero is 0.25 (DefaultProbeJitter); a negative value is a
	// jitter of 0, the fixed schedule.
	ProbeJitter float64
}

Liveness are the settings that judge whether a session and its pipes are alive: Config.Liveness, and Conn.SetLiveness while the session runs. The zero value of each field is its default and a negative value its off setting where it has one; other values outside a field's range are invalid (ErrInvalidConfig).

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. The caller owns the returned slice.
	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 OutboundState added in v1.3.2

type OutboundState uint8

OutboundState is the state of a pipe's outbound direction in its life cycle; 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 Packet added in v1.4.7

type Packet struct {
	// Data is the payload.
	Data []byte
	// ContextID is the RFC 9297 Context ID (0 by default).
	ContextID uint64
	// Datagram reports that the packet arrived as a datagram rather than
	// as a capsule in the stream.
	Datagram bool
}

Packet is a packet of a PacketStream.

type PacketOptions added in v1.4.7

type PacketOptions struct {
	// MaxPacket is the largest payload, in bytes and without the Context
	// ID, that the stream sends and accepts (0: DefaultMaxPacket). Both
	// ends use the same value: a received capsule above it ends the stream
	// with ZMUX_PACKET_ERROR. Negative is invalid.
	MaxPacket int
	// Policy chooses how packets are sent (PacketPreferDatagram).
	Policy PacketPolicy
}

PacketOptions configure a PacketStream; the zero value is the default.

type PacketPolicy added in v1.4.7

type PacketPolicy uint8

PacketPolicy chooses how a PacketStream sends a packet.

const (
	// PacketPreferDatagram sends a packet as a datagram when the stream has
	// datagrams and the packet fits the stream's MaxDatagramPayload at
	// that moment, otherwise as a capsule in the stream. A datagram that
	// the send queue or a limiter drops is lost; it is never resent as a
	// capsule.
	PacketPreferDatagram PacketPolicy = iota
	// PacketStreamOnly sends every packet as a capsule: in order and
	// reliably.
	PacketStreamOnly
	// PacketDatagramOnly sends every packet as a datagram; one that does
	// not fit fails with *DatagramTooLargeError, and without datagrams
	// every packet fails with ErrNotNegotiated.
	PacketDatagramOnly
)

func (PacketPolicy) String added in v1.4.7

func (p PacketPolicy) String() string

String returns the policy's name ("prefer datagram").

type PacketStats added in v1.4.7

type PacketStats struct {
	// SentDatagrams and SentCapsules count the packets sent each way.
	SentDatagrams, SentCapsules uint64
	// DroppedTooLarge counts the packets PacketDatagramOnly did not send
	// because they did not fit; DroppedLimited those the session's
	// datagram send limiter refused. Datagrams dropped later, from a full
	// send queue, are counted by the session (DatagramsDroppedSend).
	DroppedTooLarge, DroppedLimited uint64
	// ReceivedDatagrams and ReceivedCapsules count the packets received
	// each way; SkippedCapsules the capsules of other types skipped.
	ReceivedDatagrams, ReceivedCapsules, SkippedCapsules uint64
}

PacketStats are the counts of a PacketStream.

type PacketStream added in v1.4.7

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

PacketStream carries packets on a bidirectional stream (EXTENSIONS.md Section 12): each packet goes either as a datagram of the stream or as an RFC 9297 DATAGRAM capsule in its bytes, with the same Context ID and payload. Packets sent as datagrams may be lost or reordered relative to the others; those sent as capsules arrive in order. Capsules of other types are skipped.

A PacketStream owns its stream: once wrapped, the stream's bytes and datagrams are read and written only through it. Its deadlines still apply. ReadPacket and WritePacket may run concurrently with each other (one reader and one writer); concurrent calls of the same method are serialized. Close, CancelRead, CancelWrite and Stats may be called at any time.

func NewPacketStream added in v1.4.7

func NewPacketStream(st *Stream, opts *PacketOptions) (*PacketStream, error)

NewPacketStream wraps a bidirectional stream, opened or accepted, as a packet stream (opts nil: the defaults). The application agrees on the stream's use with its peer, for example in the preamble.

func (*PacketStream) CancelRead added in v1.4.7

func (p *PacketStream) CancelRead(code StreamErrorCode)

CancelRead stops the receiving part with code.

func (*PacketStream) CancelWrite added in v1.4.7

func (p *PacketStream) CancelWrite(code StreamErrorCode)

CancelWrite resets the sending part with code; queued capsules are discarded.

func (*PacketStream) Close added in v1.4.7

func (p *PacketStream) Close() error

Close finishes the sending part (FIN) once queued capsules are sent; packets can still be read.

func (*PacketStream) ReadPacket added in v1.4.7

func (p *PacketStream) ReadPacket(ctx context.Context, buf []byte) (Packet, error)

ReadPacket returns the next packet, waiting until ctx ends or the read deadline passes; io.EOF once the peer finished the stream at a capsule boundary and no datagram is queued. A capsule's payload is read into buf when it fits (Data is then buf[:n]) and into a new slice otherwise; a datagram's payload is returned in its own slice. Malformed stream bytes reset and stop the stream with ZMUX_PACKET_ERROR and fail this and every later call with ErrMalformedPacket. An interrupted call loses nothing: the next one continues the capsule in progress.

func (*PacketStream) Stats added in v1.4.7

func (p *PacketStream) Stats() PacketStats

Stats returns the stream's packet counts.

func (*PacketStream) WritePacket added in v1.4.7

func (p *PacketStream) WritePacket(ctx context.Context, contextID uint64, b []byte) error

WritePacket sends a packet with Context ID contextID (0 when the application uses none) as the policy says. A datagram never blocks; a capsule waits for room in the stream until ctx ends or the write deadline passes. A ctx that has ended before the call sends nothing, and a capsule given up before its first byte is never sent later. A capsule interrupted part-way leaves the stream unusable for packets: its sending part is reset with ZMUX_CANCELLED and later writes fail.

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 {
	PipeID    PipeID
	SRTT      time.Duration
	RTTVar    time.Duration
	Rate      uint64 // 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 uint32
}

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 (*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) Close added in v1.3.0

func (p *Pipe) Close() error

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

func (*Pipe) Done added in v1.4.6

func (p *Pipe) Done() <-chan struct{}

Done returns a channel that is closed once the pipe has been removed and its carrier's work in the library has ended, or the session has ended (Wait then returns the session's error). It is closed at once for a pipe that is gone. A select on it bounds the wait with a timer or a context.

func (*Pipe) ID added in v1.3.0

func (p *Pipe) ID() PipeID

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) 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.

func (*Pipe) Update added in v1.4.5

func (p *Pipe) Update(u PipeUpdate) error

Update applies u to the pipe, all its fields together, from the next scheduling decision. An invalid value is an ErrInvalidConfig error that changes nothing; a pipe that is gone fails with ErrPipeGone. The settings in force are in the pipe statistics.

func (*Pipe) Wait added in v1.4.6

func (p *Pipe) Wait() error

Wait blocks until Done is closed and returns how the pipe ended: nil for a graceful removal (Close, or the peer's) and for a pipe that is gone, the cause for a failed or aborted one (ErrPipeGone without a known cause), and the session's error when the session ended first. Wait does not remove the pipe: it waits for Close, Abort or the pipe's own end.

func (*Pipe) WaitAttached added in v1.4.0

func (p *Pipe) WaitAttached(ctx context.Context) error

WaitAttached waits until the peer has attached the pipe, returning nil at once for a pipe it already has: the bootstrap pipe, a pipe the peer joined, or one this endpoint joined that has received a PIPE_ACK acknowledging a byte (one with only an inbound direction: a record). AddPipe waits for it unless PipeOptions.ReturnOnReply is set; until then the peer may have no state of the pipe, and closing the session's other pipes would leave it none. It returns ctx's error, ErrPipeGone once the pipe failed, closed or is gone before it is attached, or the session's error once the session ends.

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
	// 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 ErrJoinPending and the peer's
	// joins are held (ConnectionStats.JoinPending) for at most
	// JoinTimeout, 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.
	DeferredPSK bool
	// EndToEnd declares in advance what Conn.DeclareEndToEnd declares: the
	// host knows pipe 0 ends at the peer before the session starts, such as
	// on a pinned connection. Without it, and without the secure carrier,
	// there are no join keys. It is no secret source of its own, and on a
	// secure first pipe it is accepted and has no effect, so that one
	// Config serves both.
	EndToEnd bool
}

PipeAuth configures the secret sources of joins. EndToEnd is no source: it says the bootstrap carrier ends at the peer, which the exporter and a deferred PSK need to be trusted.

type PipeHint added in v1.4.0

type PipeHint struct {
	// 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
	// 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
	// Pair is the Zmux-Pipe-Pair header: the pairing token of split
	// carriers; Uplink says which half this carrier is.
	// A half waits for its partner within the handshake timeout, holding
	// its slots (ListenerConfig.MaxPending, MaxPendingPerSource) until the
	// pair is complete.
	Pair   string
	Uplink bool
}

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

type PipeID added in v1.4.5

type PipeID uint64

PipeID identifies a pipe for the life of its session; the bootstrap pipe is 0. It is an unsigned 62-bit value.

type PipeIO added in v1.3.0

type PipeIO struct {
	R io.ReadCloser
	W io.WriteCloser
	// Protocol is the application protocol the carrier negotiated other
	// than by the ALPN of a TLS handshake this process runs, such as a
	// WebSocket subprotocol (ConnectionState.ApplicationProtocol); empty
	// otherwise.
	Protocol string
	// Label names the pipe in statistics.
	Label string
	// 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
	// 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
	// HandshakePadding is the padding bytes a handshake run on the carrier
	// before this PipeIO added; the session the carrier becomes part of, by
	// starting it or by joining it, meters it once. 0: none.
	HandshakePadding uint64
	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
}

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 the Bound record mode (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;
  • 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 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 PairedPipe added in v1.4.0

func PairedPipe(up, down PipeIO) PipeIO

PairedPipe makes one carrier of two unidirectional ones, the local endpoint's uplink and downlink. The attachment fails as one.

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 SealRecords added in v1.4.0

SealRecords returns p as a carrier of Sealed records: a message carrier with one zmux record in each AEAD message, sealed by s and opened by o. mode is what the carrier reports as its RecordMode and exp its exporter (nil: none). It offers only what its halves implement here, so the carrier's lanes, datagram channel and exporter are hidden. It is the one implementation of Sealed records, for a Join and for an Establish of the secure carrier.

func SecureTLS added in v1.4.0

func SecureTLS(c *tls.Conn) PipeIO

SecureTLS returns c as a carrier that declares the Bound contract (CarrierSecure): the host states that this TLS connection ends at the peer, with no proxy that terminates it. It is for a connection the host dialled or accepted directly; renegotiation stays off, the default of crypto/tls. The declaration is judged again after the handshake: TLS 1.3, or TLS 1.2 that did not resume, and a missing extended master secret fails the export.

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). A stream opened locally may be wrapped too: set its preamble first (SetPreamble for OPEN_INFO, SetPipeCarrier, AddPreambleTLV), before the nested session writes.

type PipeLiveness added in v1.3.3

type PipeLiveness struct {
	// SuspectFloor is at least 50 ms.
	SuspectFloor time.Duration
	// DeadTimeout is at least 1 s.
	DeadTimeout time.Duration
	// ProbeInterval is the probe interval of the pipe while it is idle,
	// measured to the carrier: with a shaping delay of up to H, probes wait
	// k_eff = max(1 s, k - H). A negative value turns the pipe's idle
	// probes off; otherwise at least 1 s. On a pipe without an outbound
	// direction at the peer at most 15 s takes effect, and the probes stay.
	ProbeInterval time.Duration
	// ProbeJitter is below 1; a negative value is a jitter of 0.
	ProbeJitter float64
}

PipeLiveness are a pipe's own liveness settings (PipeOptions.Liveness, PipeUpdate.Liveness, PoolDecision.Liveness), the Liveness fields that apply to one pipe with their meanings and bounds; a zero field follows the session's.

type PipeOptions added in v1.3.0

type PipeOptions struct {
	// Label names the pipe in statistics.
	Label string
	// Liveness are the pipe's own liveness settings; a zero field follows
	// the session's (Config.Liveness). Default: the session's.
	Liveness Change[PipeLiveness]
	// QualityBand is the pipe's own quality band for EventPipeQualityChanged
	// (its outbound direction). Default: the session's (Conn.SetQualityBand).
	// A receive-only pipe has none: setting it is an ErrInvalidConfig error.
	QualityBand Change[QualityBand]
	// SendPriority is the tier of the local outbound direction (lower is
	// preferred). Default: the peer's request, else tier 0.
	SendPriority Change[uint64]
	// ReceivePriority is the tier requested for the peer's outbound
	// direction. Default: tier 0.
	ReceivePriority Change[uint64]
	// Weight is the share for SchedulerSpreadRoundRobin and the factor of
	// SchedulerSpreadRateWeighted. Default 1; 0 excludes the pipe unless
	// every candidate has 0.
	Weight Change[uint64]
	// Probation is the base of the pipe's probation. Default (and Set(0)):
	// the session's (SchedulerParams.Probation); a negative value turns
	// the pipe's probation off.
	Probation Change[time.Duration]
	// 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
	// KeyGroup is the key-exchange group of the Join's key share. Zero:
	// group 1 when it is usable, otherwise group 2. A group that is not
	// usable in the session fails AddPipe with ErrInvalidConfig.
	KeyGroup uint64
	// SendStandby makes the local outbound direction carry data only on
	// failover. Default: the peer's request, else active.
	SendStandby Change[bool]
	// ReceiveStandby asks the peer to make its outbound direction standby.
	// Default: active.
	ReceiveStandby Change[bool]
	// RecordMode is the record mode of this carrier. Default:
	// Config.RecordPolicy, else RecordSealed.
	RecordMode Change[RecordMode]
	// Direction from the local endpoint: DirectionBidirectional (the zero
	// value), DirectionSendOnly (an uplink) or DirectionReceiveOnly (a downlink).
	Direction Direction
	// ReturnOnReply makes AddPipe return at the verified Reply instead of
	// once the peer has attached the pipe. The caller then keeps the
	// session's other pipes until Pipe.WaitAttached returns.
	ReturnOnReply 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 fields of PipeUpdate (SendPriority, ReceivePriority, SendStandby, ReceiveStandby, Weight, Probation, Liveness, QualityBand) and RecordMode are Change values of the same types as in PipeUpdate: at AddPipe the zero Change and Clear both mean the default and Set gives a value, the zero value included, as in SendStandby: Set(true) or Weight: Set(uint64(0)). A set Send field wins over the peer's request (PIPE_STATUS), which can change at any time; the Receive fields are always sent: the Hello carries a request for the peer's outbound direction.

type PipePool added in v1.3.0

type PipePool struct {
	// Policy, when set, is asked on every pass of the pool; its
	// DialAfter replaces the backoff, bounded by Backoff.Max, and its
	// Liveness applies 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
	// 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
	// (zmuxhttp.Split.Join), with the options given; the member is usable while
	// all of them are, and they are replaced together. ctx bounds the
	// joins; o has ReturnOnReply set, as the pool's own joins do.
	Join func(ctx context.Context, c *Conn, o PipeOptions) ([]*Pipe, error)
	// ChoicePolicy is the policy of Choice (nil: the defaults, with a cache
	// private to the pool); its Join does not apply.
	ChoicePolicy *CarrierChoicePolicy
	// 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)
	// Choice, 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.CarrierCredential. Stable first,
	// then upgrade: a member is dialed over the most robust kind available
	// (a kind CarrierChoicePolicy.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
	// CarrierChoicePolicy.Settle. A kind whose join fails, whose replacement ends
	// before it settled, or whose member fails within
	// CarrierChoicePolicy.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. ExplicitChoice dials its one kind only, without
	// the cache.
	Choice CarrierChoice
	// 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, jitter
	// 0.2 when unset), 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 the
	// jitter, drawn once per wait. The zero value selects the defaults: no
	// backoff would redial a failing path in a busy loop.
	Backoff Backoff
	// Count is the number of usable pipes to keep (0: 1, as a pool of no
	// pipes has nothing to maintain).
	Count int
}

PipePool keeps pipes of one path up.

type PipeStats added in v1.3.0

type PipeStats struct {
	PipeID     PipeID
	FateGroup  uint64
	Label      string
	Variant    string     // PipeIO.Variant
	RecordMode RecordMode // who protects its records
	Local      bool       // this endpoint joined the attachment
	// PeerAttached reports that the peer has attached the pipe
	// (WaitAttached); once true it stays true.
	PeerAttached bool
	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. Fields marked estimate are the sender's estimators 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 PipeStreamOptions added in v1.4.2

type PipeStreamOptions struct {
	// Info is the stream's OPEN_INFO (nil: none).
	Info []byte
	// TLVs are application TLVs (for example routing metadata for
	// relays); PIPE_CARRIER is added.
	TLVs []TLV
}

PipeStreamOptions is the opening preamble of a carrier stream.

type PipeUpdate added in v1.4.5

type PipeUpdate struct {
	SendPriority    Change[uint64]
	ReceivePriority Change[uint64]
	SendStandby     Change[bool]
	ReceiveStandby  Change[bool]
	Weight          Change[uint64]
	Probation       Change[time.Duration]
	Liveness        Change[PipeLiveness]
	QualityBand     Change[QualityBand]
}

PipeUpdate changes a live pipe's runtime settings in one call (Pipe.Update). Every field is a Change; a field left at its zero value keeps its setting. Set and Clear mean, per field:

  • SendPriority, SendStandby (the local outbound direction): set wins over the peer's request; clear follows the peer's latest PIPE_STATUS request, else the default (tier 0, active). Nothing is sent.
  • ReceivePriority, ReceiveStandby (the request for the peer's outbound direction): set requests the value, clear the default (tier 0, active); a PIPE_STATUS is sent when the request differs from the one in force, at once while the pipe is ACTIVE and when it becomes ACTIVE otherwise. One call that changes both sends one PIPE_STATUS.
  • Weight: set to v (0 excludes the pipe); clear is 1.
  • Probation: set to v in the forms of PipeOptions.Probation (negative: off; zero: the session's); clear follows the session's.
  • Liveness: set replaces the pipe's own PipeLiveness as a whole; clear follows the session's. A pipe already suspect keeps the SuspectFloor and DeadTimeout it turned suspect under.
  • QualityBand: set replaces the pipe's own band; clear follows the session's (Conn.SetQualityBand). Nothing is sent. A pipe without an outbound direction refuses either with ErrInvalidConfig.

The fields fixed when the pipe is added (Direction, RecordMode, KeyGroup, Label, FateGroup, ReturnOnReply) are not in PipeUpdate.

type PipeWrapper added in v1.4.0

type PipeWrapper interface {
	WrapPipe(ctx context.Context, p PipeIO, hint PipeHint) (PipeIO, error)
}

PipeWrapper is a ListenerConfig.WrapPipe.

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, unless that error is a timeout: the end of a session never matches a timeout.

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, or nil when it is a timeout.

type PoolDecision added in v1.3.2

type PoolDecision struct {
	// RetirePipes lists the pipes of a PipePool to retire now (a pipe is
	// replaced before it closes); RetireConnections lists the connections
	// of a carrier.ConnPool to retire, by fate group.
	RetirePipes       []PipeID
	RetireConnections []uint64
	// Liveness is set on the pipes a pool dials after this decision, over
	// its PipeOptions.Liveness: a zero field keeps the pool's (else the
	// session's) setting, and the others take the forms and bounds of
	// PipeLiveness (a negative ProbeInterval turns their idle probes off).
	// A pool that dials no pipes ignores it. Validate reports values
	// outside these bounds, which a pool (or Config.RedialPolicy's session)
	// does not clamp: it rejects the whole decision and reports the error
	// to its DecisionRejected callback.
	Liveness PipeLiveness
	// 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
	// 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
}

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

func (*PoolDecision) Ask added in v1.4.5

func (d *PoolDecision) Ask(pol PoolPolicy, v *PoolView) error

Ask fills d with pol's decision on v, as every pool asks its policy: a panic in Decide is contained (the zero decision then applies), and the error is the decision's Validate error, the decision left as it is; a pool that rejects the decision goes on as with the zero one.

func (*PoolDecision) RecheckAfter added in v1.4.5

func (d *PoolDecision) RecheckAfter() time.Duration

RecheckAfter is the wait d asks for before the next Decide, Recheck raised to MinRecheck; 0: none.

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, or a Liveness outside the bounds of PipeLiveness.

type PoolMember added in v1.3.2

type PoolMember struct {
	// PipeID is the pipe of a PipePool member; FateGroup the fate group
	// of a carrier.ConnPool connection. The other is zero.
	PipeID    PipeID
	FateGroup uint64
	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 carrier.ConnPool.

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
	LastDial time.Time // zero: none
	Members  []PoolMember
	Failures int // consecutive failed dials
	// Connections reports a carrier.ConnPool: its members are connections,
	// named by FateGroup and retired with RetireConnections. Otherwise they
	// are the pipes of a PipePool, named by PipeID and retired with
	// RetirePipes.
	Connections bool
}

PoolView is the state of a pool.

type PreambleTooLargeError added in v1.3.2

type PreambleTooLargeError struct{ Max int64 }

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 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; a negative value sets no minimum.
	MinInterval time.Duration
}

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) PreamblePriority added in v1.4.2

func (s *ReceiveStream) PreamblePriority() (urgency Urgency, incremental, ok bool)

PreamblePriority returns the peer's opening PRIORITY, as Stream.PreamblePriority.

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 RecordMode added in v1.4.0

type RecordMode uint8

RecordMode says who protects a carrier's records. The order is from strongest to weakest.

const (
	// RecordSealed protects records with the handshake's keys.
	RecordSealed RecordMode = 0
	// RecordBound leaves records to the carrier and binds its exporter into
	// the handshake.
	RecordBound RecordMode = 1
	// RecordTrusted leaves records to the deployment; both ends configure it
	// explicitly.
	RecordTrusted RecordMode = 2
	// RecordUnmanaged is a first pipe without the secure carrier. It is only
	// reported: no Join has this mode.
	RecordUnmanaged RecordMode = 3
)

The record modes; the values are those of the Mode field of a Join (secure-carrier Section 11).

func (RecordMode) String added in v1.4.0

func (m RecordMode) String() string

String returns "sealed", "bound", "trusted" or "unmanaged".

type RecordOpener added in v1.4.5

type RecordOpener interface {
	// Open appends the opened ciphertext to dst; an error is an
	// authentication failure, which fails the carrier for good.
	Open(dst, ciphertext []byte) ([]byte, error)
}

RecordOpener opens the records one direction of a carrier receives, as a RecordSealer of the peer sealed them.

type RecordPolicy added in v1.4.0

type RecordPolicy func(c RecordPolicyInput) RecordMode

RecordPolicy chooses the record mode of a carrier the local endpoint joins.

type RecordPolicyInput added in v1.4.5

type RecordPolicyInput struct {
	// Label is the carrier's PipeIO.Label.
	Label string
	// HasExporter reports that the carrier has a keying material exporter.
	HasExporter bool
	// Secure reports that the carrier declares the Bound contract
	// (CarrierSecure).
	Secure bool
	// IsFirstPipe reports that the carrier is the session's first pipe.
	IsFirstPipe bool
}

RecordPolicyInput describes a carrier to RecordPolicy and AllowRecordMode.

type RecordSealer added in v1.4.5

type RecordSealer interface {
	// Overhead is the bytes Seal adds to a plaintext.
	Overhead() int
	// Seal appends the sealed plaintext to dst.
	Seal(dst, plaintext []byte) ([]byte, error)
}

RecordSealer seals the records one direction of a carrier sends, one AEAD message per record, with nonces of its own.

type RejectAction added in v1.4.0

type RejectAction uint8

RejectAction is the answer of ListenerConfig.OnReject.

const (
	// RejectClose closes the carrier.
	RejectClose RejectAction = iota
	// RejectStall holds the carrier, silent (ListenerConfig.OnReject says until when).
	RejectStall
)

type RejectError added in v1.4.0

type RejectError struct {
	Err        error
	Reason     string
	Profile    uint64
	RecordMode RecordMode
}

RejectError is what a WrapPipe returns to refuse an unauthenticated carrier: the carrier then goes to OnReject, and WrapPipe does not close it. Err is the underlying error, if any.

func (*RejectError) Error added in v1.4.0

func (e *RejectError) Error() string

func (*RejectError) Unwrap added in v1.4.0

func (e *RejectError) Unwrap() error

Unwrap returns Err.

type RejectInfo added in v1.4.0

type RejectInfo struct {
	// Err is the underlying error of a transform's rejection
	// (RejectError.Err), nil for a join.
	Err        error
	Src        netip.AddrPort
	Reason     string     // "unknown_locator", "unknown_suite", "auth", "pending_limit" or the like
	Profile    uint64     // 2 for a Join
	RecordMode RecordMode // the mode its Hello names
}

RejectInfo describes an unauthenticated carrier to ListenerConfig.OnReject.

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, unless that error is a timeout: the end of a session never matches a timeout.

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, or nil when it is a timeout.

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 int64         // 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 and attached by the peer (Pipe.WaitAttached): 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 SchedulerAffinity, SchedulerSessionAffinity, SchedulerSpreadETA, SchedulerSpreadRoundRobin and SchedulerSpreadRateWeighted.

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.SchedulerSessionAffinity()} // 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.SchedulerSpreadRateWeighted())
	fmt.Println(len(client.PipeStats()))
}
Output:
1

func SchedulerAffinity added in v1.4.5

func SchedulerAffinity() Scheduler

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

func SchedulerCustom added in v1.4.5

func SchedulerCustom(p Pick) Scheduler

SchedulerCustom returns a scheduler that asks p.

func SchedulerSessionAffinity added in v1.4.5

func SchedulerSessionAffinity() Scheduler

SchedulerSessionAffinity uses one active pipe per tier.

func SchedulerSpreadETA added in v1.4.5

func SchedulerSpreadETA() Scheduler

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

func SchedulerSpreadRateWeighted added in v1.4.5

func SchedulerSpreadRateWeighted() Scheduler

SchedulerSpreadRateWeighted shares chunks by weight times measured rate.

func SchedulerSpreadRoundRobin added in v1.4.5

func SchedulerSpreadRoundRobin() Scheduler

SchedulerSpreadRoundRobin shares chunks by the pipes' weights.

type SchedulerParams added in v1.3.0

type SchedulerParams struct {
	// Probation is the base of a pipe's probation. Zero is the default
	// (from the RTT and the pipe's history); a negative value turns
	// probation off. PipeOptions.Probation overrides it per pipe.
	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
	// SpreadChunk is the unit the spreading policies split data into, in
	// bytes. Zero is 16 KiB; a negative value is invalid.
	SpreadChunk int64
	// Redundancy sends the data of urgent stream directions (urgency 0
	// to 2) and the first chunk after an idle period redundantly on a
	// second pipe. It is on by default; SwitchOff turns it off.
	Redundancy Switch
}

SchedulerParams tune multipath scheduling, 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 {
	// Variant is the pipe's PipeIO.Variant, so that a factory can choose a
	// policy per transform.
	Variant string
	// PipeID is the pipe ID.
	PipeID PipeID
	// WriteOverhead is the pipe's PipeIO.WriteOverhead: the fixed number
	// of bytes each carrier write adds below the pipe.
	WriteOverhead int
	// 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
}

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 payload bytes forwarded
	// DatagramsDropped counts every datagram not forwarded; of them,
	// DatagramsTooLarge did not fit the next hop's MaxDatagramPayload and
	// DatagramsLimited were refused by the direction's Limiter or the next
	// session's send limiter. SplicePackets forwards datagrams that do not
	// fit as capsules instead (DatagramsEncapsulated), so its
	// DatagramsTooLarge stays 0.
	DatagramsDropped, DatagramsTooLarge, DatagramsLimited uint64
	// DatagramsEncapsulated counts the datagrams SplicePackets forwarded
	// as DATAGRAM capsules on the stream (their payload is in
	// DatagramBytes); 0 for Splice.
	DatagramsEncapsulated 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.

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 {
	// AtoB and BtoA limit the two directions (nil: none).
	AtoB, BtoA Limiter
	// Chunk is the most one direction holds at once (64 KiB; a splice
	// moves data, so 0 has no other meaning).
	Chunk int
}

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

func SplicePackets added in v1.4.7

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

SplicePackets forwards two packet streams (EXTENSIONS.md Section 12) into each other like Splice, with the same ends, limiters, bounds and result, keeping capsule boundaries: capsules are passed through as they are, their values a chunk at a time without copying, so capsules of any type, unknown ones included, reach the other side unchanged. A datagram is forwarded as a datagram when it fits the other stream's MaxDatagramPayload, and otherwise inserted between two capsules as a DATAGRAM capsule (counted in DatagramsEncapsulated). Capsules are never turned into datagrams: a packet sent reliably stays reliable. The helper does not check the capsules it forwards; the receiving end does.

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) MaxDatagramPayload added in v1.4.0

func (s *Stream) MaxDatagramPayload(contextID uint64) int

MaxDatagramPayload returns the largest stream datagram payload, with context identifier contextID, the peer accepts now; 0 when it accepts none on this stream. Before the stream has its identifier (it is assigned when the stream is announced) the value assumes the longest identifier encoding and may grow by a few bytes afterwards.

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) PreamblePriority added in v1.4.2

func (s *Stream) PreamblePriority() (urgency Urgency, incremental, ok bool)

PreamblePriority returns the urgency and incremental flag of the PRIORITY TLV the peer opened the stream with; ok is false when its preamble carried none. It reports the opening preamble only, not a later PRIORITY_UPDATE.

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. 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)
	if se, ok := errors.AsType[*zmux.StreamError](err); ok {
		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
	StreamPacketError   StreamErrorCode = 0x5a4d0004
)

Application error-code conventions.

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    PipeID
	PipeBound bool
}

StreamStats is a snapshot of a stream's statistics in payload bytes, the preamble excluded; 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 Switch added in v1.4.5

type Switch int8

Switch turns a feature that is on by default off or on. The zero value is the default; SwitchOff, or any negative value, turns the feature off, and SwitchOn, or any positive value, on.

const (
	SwitchOff Switch = -1
	SwitchOn  Switch = 1
)

The settings of a Switch other than the default.

func (Switch) On added in v1.4.5

func (s Switch) On() bool

On reports whether a feature that is on by default is on.

type TLSRecordCarrier added in v1.4.0

type TLSRecordCarrier interface{ TLSRecords() bool }

TLSRecordCarrier is a sending half whose bytes go into a TLS record layer on a byte stream, so that records are aligned to TLS records. A *tls.Conn is one without saying so; a transform that keeps the raw records of one forwards the hint.

type TLV

type TLV struct {
	Value []byte
	Type  uint64
}

TLV is an application TLV of a stream's preamble.

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 {
	ErrorMessage string
	// Details are the key=value pairs of the diagnostic line.
	Details   string
	ErrorCode TransportErrorCode
	FrameType uint64
	Remote    bool
}

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.

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. 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 zmuxhttp.Options.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) RequestSource added in v1.4.5

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

RequestSource returns the source and the peer of r: the peer is r.RemoteAddr (zero when it is not an IP address and port, such as a Unix socket), the source what t.Source resolves from it (a nil t: the peer).

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.

func (*TrustedProxies) Validate added in v1.4.5

func (t *TrustedProxies) Validate() error

Validate checks t (nil is valid) and builds its prefix set; the adapters call it when they are set up.

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 WrapPipeFunc added in v1.4.0

type WrapPipeFunc func(ctx context.Context, p PipeIO, hint PipeHint) (PipeIO, error)

WrapPipeFunc is a function used as a PipeWrapper.

func (WrapPipeFunc) WrapPipe added in v1.4.0

func (f WrapPipeFunc) WrapPipe(ctx context.Context, p PipeIO, hint PipeHint) (PipeIO, error)

WrapPipe calls f.

Directories

Path Synopsis
adapter
quicmux module
Package admit holds what a server uses to judge a carrier before any zmux handshake, and what a client presents for that judgment: ClassifyFirstBytes and FirstRecordIsLane tell zmux first records from other content in a carrier's first bytes, PrefixAuth is a credential of keyed, time-slotted tokens with its verifier (PrefixAuthVerifier, an admission decision), and ReplayFilter accepts each nonce or token once within a window.
Package admit holds what a server uses to judge a carrier before any zmux handshake, and what a client presents for that judgment: ClassifyFirstBytes and FirstRecordIsLane tell zmux first records from other content in a carrier's first bytes, PrefixAuth is a credential of keyed, time-slotted tokens with its verifier (PrefixAuthVerifier, an admission decision), and ReplayFilter accepts each nonce or token once within a window.
Package carrier holds the building blocks of carrier adapters: ConnPool shares underlying connections (HTTP/2 and HTTP/3 request streams, QUIC streams) between pipes within PoolLimits, ChannelDemux routes the datagrams of a connection shared by several pipes to their channels, and WriteFlat turns a batch of buffers into one write for a writer whose every call is costly.
Package carrier holds the building blocks of carrier adapters: ConnPool shares underlying connections (HTTP/2 and HTTP/3 request streams, QUIC streams) between pipes within PoolLimits, ChannelDemux routes the datagrams of a connection shared by several pipes to their channels, and WriteFlat turns a batch of buffers into one write for a writer whose every call is costly.
internal
carrierio
Package carrierio holds the carrier helpers that the root package uses itself and package carrier exposes: the flat batch write and the demultiplexer of channel datagrams.
Package carrierio holds the carrier helpers that the root package uses itself and package carrier exposes: the flat batch write and the demultiplexer of channel datagrams.
conformance
Package conformance runs the executable traces and the wire corpus of the zmux specification against the sans-IO core.
Package conformance runs the executable traces and the wire corpus of the zmux specification against the sans-IO core.
core
Package core is the sans-IO zmux session.
Package core is the sans-IO zmux session.
httpx
Package httpx holds what the HTTP carriers share with the root package: the request field names zmux defines, the rule for a field name a host chooses in their place (a pairing field, a prefix-authentication field), and a request body that replays bytes read before.
Package httpx holds what the HTTP carriers share with the root package: the request field names zmux defines, the rule for a field name a host chooses in their place (a pairing field, a prefix-authentication field), and a request body that replays bytes read before.
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.
join
Package join is the sans-IO core of the secure carrier's Join protocol and the primitives Establish shares with it: the suite table, Sealed records, the handshake payload codec, the first-byte dispatch and the exporter.
Package join is the sans-IO core of the secure carrier's Join protocol and the primitives Establish shares with it: the suite table, Sealed records, the handshake payload codec, the first-byte dispatch and the exporter.
labels
Package labels starts the goroutines of zmux and its adapter modules with their runtime/pprof labels, by the rules of the root package's labels.go: "zmux" is the task; a goroutine that works for one call keeps the labels of that call's context, one that outlives the call starts from context.Background() and carries zmux labels only.
Package labels starts the goroutines of zmux and its adapter modules with their runtime/pprof labels, by the rules of the root package's labels.go: "zmux" is the task; a goroutine that works for one call keeps the labels of that call's context, one that outlives the call starts from context.Background() and carries zmux labels only.
leakcheck
Package leakcheck verifies that tests leave no goroutines behind (a standard-library replacement for goleak): Check for one test, Main for a whole test binary.
Package leakcheck verifies that tests leave no goroutines behind (a standard-library replacement for goleak): Check for one test, Main for a whole test binary.
setting
Package setting resolves configuration values by the conventions that the zmux packages share.
Package setting resolves configuration values by the conventions that the zmux packages share.
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 the decisions on sizes and timing of what a session writes: Shaper for records and HandshakeShaper for handshake messages.
Package shaping defines the decisions on sizes and timing of what a session writes: Shaper for records and HandshakeShaper for handshake messages.
bundle
Package bundle reads shaping configuration documents.
Package bundle reads shaping configuration documents.
machine
Package machine runs shaping candidates: handshake plans by name, records by state machines, and a pool policy, all on one integer value form.
Package machine runs shaping candidates: handshake plans by name, records by state machines, and a pool policy, all on one integer value form.
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
Package zmuxhttp carries zmux sessions over HTTP requests, in three carrier kinds, each a struct whose methods are the operations on it: a stream carrier is one request whose body carries the up direction and whose response body the down direction (Streaming); a split carrier pairs an uplink POST and a downlink GET by a pairing field (Split); an exchange carrier is a sequence of short authenticated requests for paths that buffer or cut long ones (Exchange, with ExchangeConfig for what both ends agree on).
Package zmuxhttp carries zmux sessions over HTTP requests, in three carrier kinds, each a struct whose methods are the operations on it: a stream carrier is one request whose body carries the up direction and whose response body the down direction (Streaming); a split carrier pairs an uplink POST and a downlink GET by a pairing field (Split); an exchange carrier is a sequence of short authenticated requests for paths that buffer or cut long ones (Exchange, with ExchangeConfig for what both ends agree on).
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