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. The NextEvent queue holds at most one unread event per key (a pipe's state, a tier, a kind of session event) and never drops one; a Tracer sees every occurrence on a backlog of 256 events per session and is told how many it lost. 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 ErrDuplicateUndecided 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), the bounds of a carrier's dial and of its graceful close, 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, *zmux.Takeover),
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
}
}
Output:
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
}
}
Output:
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
}
}
Output:
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
}
}
}
Output:
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
}
}
Output:
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")
}
}
}
}
Output:
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
}
}
Output:
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.RequestSource
_ = 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
}
}
Output:
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, _ 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
}
}
Output:
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()
}()
}
}()
}
}
}
Output:
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 ¶
- Constants
- Variables
- func ALPNAlias(id string) (string, bool)
- func AdmittedAs[T any](a Admitted) (v T, ok bool)
- func BoundTLS(st tls.ConnectionState) bool
- func CancelCause(code StreamErrorCode) error
- func CheckSealedCarrier(p PipeIO) error
- func ClosePipeIO(p PipeIO)
- func EarlyRequest(r *http.Request) bool
- func HandleLane(ctx context.Context, p PipeIO) error
- func IsCarrierSecure(p PipeIO) bool
- func IsRetryable(err error) bool
- func PipeConn(p PipeIO) net.Conn
- func PresentPipe(ctx context.Context, p PipeIO, c CarrierCredential) error
- func StreamConn(s *Stream, local, remote net.Addr) net.Conn
- func TerminatedTLS(p PipeIO) (tls.ConnectionState, bool)
- type Aborter
- type Admission
- type AdmissionStage
- type AdmissionStats
- type AdmissionVerdict
- type Admitted
- type AllowRecordMode
- type ApplicationError
- type ApplicationErrorCode
- type Arrival
- func (a *Arrival) Admit(ctx context.Context, p PipeIO) (PipeIO, bool)
- func (a *Arrival) AdmitFirst(ctx context.Context, first func(context.Context) (PipeIO, error)) (PipeIO, bool)
- func (a *Arrival) Admitted() bool
- func (a *Arrival) DecideRequest(w http.ResponseWriter, r *http.Request, fallback http.Handler) bool
- func (a *Arrival) Detached() bool
- func (a *Arrival) HandlePipe(ctx context.Context, p PipeIO, hint PipeHint) error
- func (a *Arrival) HandshakeFailed()
- func (a *Arrival) PrepareCarrier(ctx context.Context, prepare func(context.Context) error) (err error)
- func (a *Arrival) Release()
- func (a *Arrival) SetupContext(parent context.Context) (ctx context.Context, unlink context.CancelFunc)
- func (a *Arrival) Take(ctx context.Context, p PipeIO, hint PipeHint) (run func(context.Context) error, err error)
- type Backoff
- type BuffersWriter
- type CacheOutcome
- type Candidate
- type CandidateOutcome
- type CandidateResult
- type CapacityFloor
- type CarrierCache
- type CarrierChoice
- type CarrierChoiceError
- type CarrierChoicePolicy
- type CarrierConner
- type CarrierCounts
- type CarrierCredential
- type CarrierDirection
- type CarrierID
- type CarrierInfo
- type CarrierKind
- type CarrierPeer
- type CarrierRecordLimit
- type CarrierRecordMode
- type CarrierSample
- type CarrierSecure
- type CarrierSource
- type CarrierTaker
- type CarrierTarget
- type Change
- type Chunk
- type CloseCodeRecorder
- type CloseWriter
- type Config
- type Conn
- func Client(ctx context.Context, c net.Conn, cfg *Config) (*Conn, error)
- func Dial(ctx context.Context, network, addr string, cfg *Config) (*Conn, error)
- func DialChoice(ctx context.Context, m CarrierChoice, cfg *Config, pol *CarrierChoicePolicy) (*Conn, error)
- func DialTLS(ctx context.Context, network, addr string, tlsConf *tls.Config, cfg *Config) (*Conn, error)
- func Server(ctx context.Context, c net.Conn, cfg *Config) (*Conn, error)
- func Start(ctx context.Context, p PipeIO, role Role, cfg *Config) (*Conn, error)
- func (c *Conn) Abort(code ApplicationErrorCode, reason string)
- func (c *Conn) AcceptStream(ctx context.Context) (*Stream, error)
- func (c *Conn) AcceptUniStream(ctx context.Context) (*ReceiveStream, error)
- func (c *Conn) Adapter() *ConnAdapter
- func (c *Conn) AddPipe(ctx context.Context, p PipeIO, o PipeOptions) (*Pipe, error)
- func (c *Conn) AdvanceEpoch() error
- func (c *Conn) CapacityFloor() CapacityFloor
- func (c *Conn) Close() error
- func (c *Conn) CloseWithError(code ApplicationErrorCode, reason string) error
- func (c *Conn) ConnectionState() ConnectionState
- func (c *Conn) ConnectionStats() ConnectionStats
- func (c *Conn) Context() context.Context
- func (c *Conn) DeclareEndToEnd()
- func (c *Conn) DesignateDialer(e Endpoint)
- func (c *Conn) Done() <-chan struct{}
- func (c *Conn) Epoch() uint64
- func (c *Conn) ExportKeyingMaterial(label string, ctxData []byte, length int) ([]byte, error)
- func (c *Conn) HandleEvents(f func(Event)) error
- func (c *Conn) HandleStreams(f func(*Stream), maxConcurrent int) error
- func (c *Conn) HandleUniStreams(f func(*ReceiveStream), maxConcurrent int) error
- func (c *Conn) ID() SessionID
- func (c *Conn) Liveness() Liveness
- func (c *Conn) LocalAddr() net.Addr
- func (c *Conn) MaintainPipes(ctx context.Context, pool PipePool) error
- func (c *Conn) NextEvent(ctx context.Context) (Event, error)
- func (c *Conn) OpenPipeStream(ctx context.Context, o *PipeStreamOptions) (PipeIO, error)
- func (c *Conn) OpenStream() (*Stream, error)
- func (c *Conn) OpenStreamSync(ctx context.Context) (*Stream, error)
- func (c *Conn) OpenUniStream() (*SendStream, error)
- func (c *Conn) OpenUniStreamSync(ctx context.Context) (*SendStream, error)
- func (c *Conn) Ping(ctx context.Context) (time.Duration, error)
- func (c *Conn) Pipe(id PipeID) (*Pipe, bool)
- func (c *Conn) PipeStats() []PipeStats
- func (c *Conn) Pipes() []*Pipe
- func (c *Conn) QualityBand() QualityBand
- func (c *Conn) RaiseIncomingStreams(bidi, uni int64) error
- func (c *Conn) ReceiveDatagram(ctx context.Context) ([]byte, error)
- func (c *Conn) ReleaseFirstFlight()
- func (c *Conn) RememberedParameters() []byte
- func (c *Conn) RemoteAddr() net.Addr
- func (c *Conn) ReplacePipes(ctx context.Context) error
- func (c *Conn) RequestPipeReplacement(id PipeID) bool
- func (c *Conn) RevalidatePipes() error
- func (c *Conn) Scheduler() Scheduler
- func (c *Conn) SendDatagram(p []byte) error
- func (c *Conn) SendDatagramWait(ctx context.Context, p []byte) error
- func (c *Conn) SessionBinding() []byte
- func (c *Conn) SetCapacityFloor(f CapacityFloor) error
- func (c *Conn) SetJoinSecret(psk []byte) error
- func (c *Conn) SetLiveness(l Liveness) error
- func (c *Conn) SetPipeShaper(pipe PipeID, s shaping.Shaper) bool
- func (c *Conn) SetQualityBand(b QualityBand) error
- func (c *Conn) SetScheduler(s Scheduler)
- func (c *Conn) SetShaper(f ShaperFactory, budget func() shaping.Budget)
- func (c *Conn) SetShapingLimits(l shaping.Limits) error
- func (c *Conn) ShapingLimits() shaping.Limits
- func (c *Conn) ShapingMeters() shaping.Meters
- func (c *Conn) ShapingStats() shaping.Stats
- func (c *Conn) Shutdown(ctx context.Context, code ApplicationErrorCode, msg string) error
- func (c *Conn) StopEvents() error
- func (c *Conn) Wait() error
- func (c *Conn) WeakestRecordMode() RecordMode
- type ConnAdapter
- type ConnectionState
- type ConnectionStater
- type ConnectionStats
- type DatagramChannel
- type DatagramLimiter
- type DatagramTooLargeError
- type Decision
- type Direction
- type DuplicateOptions
- type DuplicateResult
- type EarlyClientCarrier
- type EarlyData
- type EarlyDataRejectedError
- type EarlyServerCarrier
- type Endpoint
- type Event
- type EventKind
- type FailureReporter
- type Framing
- type GoAway
- type HandshakeTimeoutError
- type Handshaker
- type IdleTimeoutError
- type InboundState
- type JoinAuthReason
- type KeyingMaterialExporter
- type LaneOpener
- type LaneStats
- type Limiter
- type Listener
- func (l *Listener) Accept(ctx context.Context) (*Conn, error)
- func (l *Listener) Adapter() *ListenerAdapter
- func (l *Listener) Close() error
- func (l *Listener) Drain(msg string)
- func (l *Listener) HandlePipe(ctx context.Context, p PipeIO, hint PipeHint) error
- func (l *Listener) Limits() ListenerLimits
- func (l *Listener) Serve(ctx context.Context, ln net.Listener) error
- func (l *Listener) SetLimits(lim ListenerLimits) error
- func (l *Listener) Shutdown(ctx context.Context, code ApplicationErrorCode, msg string) error
- func (l *Listener) Stats() ListenerStats
- func (l *Listener) Undrain()
- func (l *Listener) VariantStats() []VariantStat
- type ListenerAdapter
- func (a *ListenerAdapter) AdmitRequest(w http.ResponseWriter, r *http.Request, trusted *TrustedProxies, ...) (*Arrival, bool)
- func (a *ListenerAdapter) AdmitUpgrade(w http.ResponseWriter, r *http.Request, trusted *TrustedProxies, ...) (*Arrival, bool)
- func (a *ListenerAdapter) Arrive(source, peer netip.AddrPort) (*Arrival, error)
- func (a *ListenerAdapter) ChargeMemory(delta int64)
- func (a *ListenerAdapter) Clock() timeshim.Clock
- func (a *ListenerAdapter) CountSetupFailure()
- func (a *ListenerAdapter) FirstRecordTimeout() time.Duration
- func (a *ListenerAdapter) HandshakeTimeout() time.Duration
- func (a *ListenerAdapter) HasAdmission() bool
- func (a *ListenerAdapter) KnownJoin(prefix []byte) (known bool, need int)
- func (a *ListenerAdapter) MemoryPressure() bool
- func (a *ListenerAdapter) MemoryUsed() int64
- func (a *ListenerAdapter) StallDuration(source netip.AddrPort) time.Duration
- type ListenerConfig
- type ListenerLimits
- type ListenerStats
- type Liveness
- type MessageBatchWriter
- type MessageReader
- type MessageWriter
- type NetConner
- type OutboundState
- type Packet
- type PacketOptions
- type PacketPolicy
- type PacketStats
- type PacketStream
- func (p *PacketStream) CancelRead(code StreamErrorCode)
- func (p *PacketStream) CancelWrite(code StreamErrorCode)
- func (p *PacketStream) Close() error
- func (p *PacketStream) ReadPacket(ctx context.Context, buf []byte) (Packet, error)
- func (p *PacketStream) Stats() PacketStats
- func (p *PacketStream) WritePacket(ctx context.Context, contextID uint64, b []byte) error
- type PeerRequest
- type Pick
- type PickAnswer
- type PickPipe
- type PickRequest
- type Pipe
- func (p *Pipe) Abort() error
- func (p *Pipe) Close() error
- func (p *Pipe) Done() <-chan struct{}
- func (p *Pipe) ID() PipeID
- func (p *Pipe) Options() PipeOptions
- func (p *Pipe) Revalidate() error
- func (p *Pipe) Stats() (PipeStats, bool)
- func (p *Pipe) Update(u PipeUpdate) error
- func (p *Pipe) Wait() error
- func (p *Pipe) WaitAttached(ctx context.Context) error
- type PipeAuth
- type PipeHint
- type PipeID
- type PipeIO
- type PipeLiveness
- type PipeOptions
- type PipePathQualityReason
- type PipePool
- type PipeStats
- type PipeStreamOptions
- type PipeUpdate
- type PipeWrapper
- type PipesLostError
- type PoolDecision
- type PoolMember
- type PoolPolicy
- type PoolView
- type PreambleTooLargeError
- type QUICCounters
- type QualityBand
- type ReceiveStream
- func (s *ReceiveStream) CancelRead(code StreamErrorCode)
- func (s *ReceiveStream) NotifyReadable(f func()) (stop func() bool)
- func (s *ReceiveStream) PeerPriority() (urgency Urgency, incremental, ok bool)
- func (s *ReceiveStream) Preamble() []byte
- func (s *ReceiveStream) PreamblePriority() (urgency Urgency, incremental, ok bool)
- func (s *ReceiveStream) PreambleTLVs() []TLV
- func (s *ReceiveStream) Read(p []byte) (int, error)
- func (s *ReceiveStream) ReadChunk(ctx context.Context, n int) (Chunk, error)
- func (s *ReceiveStream) ReceiveWindow() (initial, limit uint64)
- func (s *ReceiveStream) Reject()
- func (s *ReceiveStream) Replayable() bool
- func (s *ReceiveStream) SetPeerPriority(urgency Urgency, incremental bool) error
- func (s *ReceiveStream) SetReadDeadline(t time.Time) error
- func (s *ReceiveStream) SetReceiveWindow(initial, limit uint64) error
- func (s *ReceiveStream) Stats() StreamStats
- func (s *ReceiveStream) StreamID() StreamID
- func (s *ReceiveStream) TryRead(p []byte) (int, error)
- func (s *ReceiveStream) WaitReadable(ctx context.Context) error
- func (s *ReceiveStream) WriteTo(w io.Writer) (int64, error)
- type RecordMode
- type RecordOpener
- type RecordPolicy
- type RecordPolicyInput
- type RecordSealer
- type RejectAction
- type RejectError
- type RejectInfo
- type ResumeTimeoutError
- type Role
- type Rotation
- type Scheduler
- type SchedulerParams
- type SendStream
- func (s *SendStream) AddPreambleTLV(t uint64, v []byte) error
- func (s *SendStream) CancelWrite(code StreamErrorCode)
- func (s *SendStream) ClearRedundant()
- func (s *SendStream) Close() error
- func (s *SendStream) Flush() error
- func (s *SendStream) Priority() (urgency Urgency, incremental bool)
- func (s *SendStream) ReadFrom(r io.Reader) (int64, error)
- func (s *SendStream) Redundant() (on, set bool)
- func (s *SendStream) Scheduler() Scheduler
- func (s *SendStream) SendBuffer() int
- func (s *SendStream) SendCapacity() uint64
- func (s *SendStream) SetPreamble(b []byte) error
- func (s *SendStream) SetPriority(urgency Urgency, incremental bool)
- func (s *SendStream) SetRedundant(on bool)
- func (s *SendStream) SetReliableBoundary()
- func (s *SendStream) SetScheduler(p Scheduler)
- func (s *SendStream) SetSendBuffer(n uint64)
- func (s *SendStream) SetWriteDeadline(t time.Time) error
- func (s *SendStream) Stats() StreamStats
- func (s *SendStream) StreamID() StreamID
- func (s *SendStream) TryWrite(p []byte) (int, error)
- func (s *SendStream) TryWriteAll(p []byte) (bool, error)
- func (s *SendStream) WaitSendCapacity(ctx context.Context, n uint64) (uint64, error)
- func (s *SendStream) WaitWritable(ctx context.Context) (uint64, error)
- func (s *SendStream) Write(p []byte) (int, error)
- func (s *SendStream) WriteChunk(ctx context.Context, c Chunk) error
- type SessionError
- type SessionID
- type ShapedPipe
- type ShaperFactory
- type SpliceDirection
- type SpliceEnd
- type SpliceEndKind
- type SpliceOptions
- type SpliceResult
- type Stream
- func (s *Stream) AddPreambleTLV(t uint64, v []byte) error
- func (s *Stream) CancelRead(code StreamErrorCode)
- func (s *Stream) CancelWrite(code StreamErrorCode)
- func (s *Stream) ClearRedundant()
- func (s *Stream) Close() error
- func (s *Stream) Context() context.Context
- func (s *Stream) Flush() error
- func (s *Stream) MaxDatagramPayload(contextID uint64) int
- func (s *Stream) NotifyReadable(f func()) (stop func() bool)
- func (s *Stream) PathDatagramPayload(contextID uint64) int
- func (s *Stream) PeerPriority() (urgency Urgency, incremental, ok bool)
- func (s *Stream) PipeCarrier() bool
- func (s *Stream) Preamble() []byte
- func (s *Stream) PreamblePriority() (urgency Urgency, incremental, ok bool)
- func (s *Stream) PreambleTLVs() []TLV
- func (s *Stream) Priority() (urgency Urgency, incremental bool)
- func (s *Stream) Read(p []byte) (int, error)
- func (s *Stream) ReadChunk(ctx context.Context, n int) (Chunk, error)
- func (s *Stream) ReadFrom(r io.Reader) (int64, error)
- func (s *Stream) ReceiveDatagram(ctx context.Context) (uint64, []byte, error)
- func (s *Stream) ReceiveWindow() (initial, limit uint64)
- func (s *Stream) Redundant() (on, set bool)
- func (s *Stream) Reject()
- func (s *Stream) Replayable() bool
- func (s *Stream) Scheduler() Scheduler
- func (s *Stream) SendBuffer() int
- func (s *Stream) SendCapacity() uint64
- func (s *Stream) SendDatagram(contextID uint64, p []byte) error
- func (s *Stream) SendDatagramWait(ctx context.Context, contextID uint64, p []byte) error
- func (s *Stream) SetDeadline(t time.Time) error
- func (s *Stream) SetPeerPriority(urgency Urgency, incremental bool) error
- func (s *Stream) SetPipeCarrier() error
- func (s *Stream) SetPreamble(b []byte) error
- func (s *Stream) SetPriority(urgency Urgency, incremental bool)
- func (s *Stream) SetReadDeadline(t time.Time) error
- func (s *Stream) SetReceiveWindow(initial, limit uint64) error
- func (s *Stream) SetRedundant(on bool)
- func (s *Stream) SetReliableBoundary()
- func (s *Stream) SetScheduler(p Scheduler)
- func (s *Stream) SetSendBuffer(n uint64)
- func (s *Stream) SetWriteDeadline(t time.Time) error
- func (s *Stream) Stats() StreamStats
- func (s *Stream) StreamID() StreamID
- func (s *Stream) TryRead(p []byte) (int, error)
- func (s *Stream) TryWrite(p []byte) (int, error)
- func (s *Stream) TryWriteAll(p []byte) (bool, error)
- func (s *Stream) WaitReadable(ctx context.Context) error
- func (s *Stream) WaitSendCapacity(ctx context.Context, n uint64) (uint64, error)
- func (s *Stream) WaitWritable(ctx context.Context) (uint64, error)
- func (s *Stream) Write(p []byte) (int, error)
- func (s *Stream) WriteChunk(ctx context.Context, c Chunk) error
- func (s *Stream) WriteTo(w io.Writer) (int64, error)
- type StreamError
- type StreamErrorCode
- type StreamErrorKind
- type StreamID
- type StreamLimitReachedError
- type StreamStats
- type Switch
- type TCPPacketCounters
- type TCPSegmentCounters
- type TLSRecordCarrier
- type TLV
- type Takeover
- type Tracer
- type TransportError
- type TransportErrorCode
- type TrustedProxies
- func (t *TrustedProxies) Listener(ln net.Listener) net.Listener
- func (t *TrustedProxies) RequestSource(r *http.Request) (source, peer netip.AddrPort)
- func (t *TrustedProxies) Source(r *http.Request, peer netip.AddrPort) netip.AddrPort
- func (t *TrustedProxies) Trusts(a netip.Addr) bool
- func (t *TrustedProxies) Validate() error
- type UnsentReporter
- type Urgency
- type VariantStat
- type WrapPipeFunc
Examples ¶
- Package (ReadmeAdmission)
- Package (ReadmeClient)
- Package (ReadmeClosing)
- Package (ReadmeErrors)
- Package (ReadmeHTTPExchange)
- Package (ReadmeMultipath)
- Package (ReadmePipeUpdate)
- Package (ReadmeProxy)
- Package (ReadmeRedial)
- Package (ReadmeServer)
- Package (Tcp)
- Package (WebSocket)
- Conn.AddPipe
- Conn.SendDatagram
- Conn.Shutdown
- DialTLS
- EarlyData
- Scheduler
- Splice
- Stream.SetPreamble
- StreamConn
- StreamError
- TransportError
Constants ¶
const ( CarrierSourceUnknown = carrierstats.SourceUnknown CarrierSourceLinuxTCPInfo = carrierstats.SourceLinuxTCPInfo CarrierSourceDarwinTCPConnectionInfo = carrierstats.SourceDarwinTCPConnectionInfo CarrierSourceWindowsSIOTCPInfo = carrierstats.SourceWindowsSIOTCPInfo CarrierSourceQUICGo = carrierstats.SourceQUICGo )
Native carrier source tags.
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 // DefaultMaxLanes is the default Config.MaxLanes, the lanes accepted // per inbound pipe. DefaultMaxLanes = core.DefaultMaxLanes // DefaultRecoveryRatio is the default CapacityFloor.RecoveryRatio. DefaultRecoveryRatio = core.DefaultRecoveryRatio // DefaultMinInterval is the default QualityBand.MinInterval. DefaultMinInterval = time.Duration(core.DefaultMinInterval) // DefaultFirstRecordTimeout is the default ListenerConfig.FirstRecordTimeout, // and the time HandleLane waits for a lane's header. DefaultFirstRecordTimeout = time.Duration(core.DefaultFirstRecordTimeout) // 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.
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).
const ( // PipePathQualityUnknown lacks enough current evidence to classify the episode. PipePathQualityUnknown = PipePathQualityReason(core.PathQualityUnknown) // PipePathQualityHealthySibling found a recently healthy outbound sibling in the same fate group. PipePathQualityHealthySibling = PipePathQualityReason(core.PathQualityHealthySibling) // PipePathQualityLocalStall found a write stall or sustained queue on this connection with no observed RTT rise. PipePathQualityLocalStall = PipePathQualityReason(core.PathQualityLocalStall) PipePathQualityShared = PipePathQualityReason(core.PathQualityShared) // PipePathQualityRestored reports that recent measurements cleared the deterioration. PipePathQualityRestored = PipePathQualityReason(core.PathQualityRestored) )
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) )
Outbound states, mirroring the core.
const ( InboundNone = InboundState(core.InNone) InboundJoining = InboundState(core.InJoining) InboundOpen = InboundState(core.InOpen) InboundEnded = InboundState(core.InEnded) )
Inbound states, mirroring the core.
const CarrierOutbound = carrierstats.Outbound
CarrierOutbound is the local sending direction.
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.
const DefaultMaxPacket = 65535
DefaultMaxPacket is the default PacketOptions.MaxPacket.
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.
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.
const MaxInstanceIDLen = 8
MaxInstanceIDLen bounds ListenerConfig.InstanceID so that at least 8 random bytes remain in the 16-byte session locator.
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.
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".
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.
const MaxWriteOverhead = 65535
MaxWriteOverhead is the largest PipeIO.WriteOverhead.
const MinMaxRecord = wire.RecordFloor
MinMaxRecord is the carrier record floor: every carrier of a pipe, each lane included, takes records of this many bytes, so it is the smallest nonzero PipeIO.MaxRecord and the smallest limit a carrier may report (CarrierRecordLimit, less the overhead of a record transform). Every frame that cannot be split across records fits one record of it.
const MinRecheck = 10 * time.Millisecond
MinRecheck is the shortest wait a pool applies to PoolDecision.Recheck.
const QMuxVersion = "draft-02"
QMuxVersion is the QMux version zmux implements, the one ConnectionState reports.
const SealedMaxRecord = join.MaxMessage - 16
SealedMaxRecord is the largest Sealed record plaintext.
Variables ¶
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.
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") // ErrHandlerRegistered means a callback owns this accept direction or event queue. ErrHandlerRegistered = errors.New("zmux: handler already registered") // ErrMessageTooLarge is returned by MessageReader.ReadMessage 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") // ErrConnectionRefused matches a CONNECTION_REFUSED transport close. ErrConnectionRefused = errors.New("zmux: connection refused") // ErrJoinTimeout identifies a join that exceeded Config.JoinTimeout. ErrJoinTimeout = core.ErrJoinTimeout // ErrJoinEvicted identifies an authorized join displaced before confirmation. ErrJoinEvicted = errors.New("zmux: unconfirmed join evicted") // ErrJoinRefused is returned by AddPipe when the peer's Reply refused the join. ErrJoinRefused = core.ErrJoinRefused // 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 = core.ErrPipeGone // ErrPipeAborted is what Pipe.Wait returns for a pipe this endpoint // removed abruptly with Pipe.Abort or to make room for another. // It also matches ErrPipeGone through errors.Is. ErrPipeAborted = core.ErrPipeAborted // ErrDuplicateUndecided is returned by ResolveDuplicate when the two // sessions have the same dialer or no input of the duplicate-session // rule decides between them. It is an argument error: it matches // ErrInvalidConfig, and the caller can supply the identities that // decide (DuplicateOptions). ErrDuplicateUndecided = fmt.Errorf("%w: the duplicate-session rule has no input that decides", ErrInvalidConfig) )
Errors of individual calls.
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") )
var ErrTakeoverReturned = errors.New("zmux: Takeover.Detach after Fallback returned")
ErrTakeoverReturned is Takeover.Detach called after Fallback returned without it: zmux has closed the carrier.
var ErrWouldBlock error = wouldBlockError{}
ErrWouldBlock is returned by TryRead when nothing is readable yet and the receiving part has neither ended nor failed. Its WouldBlock method reports true, so code that tests for that method (errors.As) recognises it without importing this package.
Functions ¶
func ALPNAlias ¶ added in v1.3.2
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
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 CancelCause ¶ added in v1.4.8
func CancelCause(code StreamErrorCode) error
CancelCause returns an error carrying code, for context.WithCancelCause: Splice and SplicePackets end both streams of both directions with the code of a cancellation cause (a *StreamError's ErrorCode, wrapped or not).
func CheckSealedCarrier ¶ added in v1.4.10
CheckSealedCarrier reports whether p, the carrier of a Sealed pipe, has the record limit Sealed needs once the AEAD sealing is added to each record (ErrInvalidConfig naming the limit). A handshake that ends in SealRecords calls it before it begins, so that a carrier too small for Sealed fails before any handshake byte is written, not after.
func ClosePipeIO ¶ added in v1.4.10
func ClosePipeIO(p PipeIO)
ClosePipeIO closes a carrier's halves: W, then R unless it is W. Each call closes each distinct half once; it is not idempotent, so the holders of one carrier must agree on which of them closes it. R and W are one half when they are the same comparable value (a pointer, as a net.Conn usually is); one value of a type that cannot be compared (a struct holding a slice, say) counts as two halves and is closed twice.
func EarlyRequest ¶ added in v1.4.5
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
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, and so is one whose first record, the lane header, does not arrive within DefaultFirstRecordTimeout (the session is not known before the header is read, so a listener's FirstRecordTimeout cannot apply). It blocks until the lane ends.
func IsCarrierSecure ¶ added in v1.4.0
IsCarrierSecure reports the Secure declaration of a carrier; a split carrier needs it on both halves.
func IsRetryable ¶ added in v1.3.0
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
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 (each of at most MaxRecordSize bytes, the largest any zmux layer writes). 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, also beside zmux closing the p it handed to WrapPipe; 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
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)
srv := make(chan *zmux.Conn, 1)
go func() {
s, err := zmux.Server(ctx, b, scfg)
srv <- s
ch <- err
}()
client, err = zmux.Client(ctx, a, ccfg)
server = <-srv
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, and after a graceful Close whose work (a final flush, a TLS close_notify) has not ended within the close bound, to end what that Close left running.
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, once more after each
// VerdictMore and once more after a VerdictDefer, concurrently for
// different carriers, outside every lock; info is each call's own
// copy. Decide must return once ctx ends: one that does not keeps its
// goroutine, the request and prefix past the carrier's end.
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 of a byte stream read before Decide (0:
// none). Decide receives fewer when the carrier ends first. On a
// message-framed carrier any Peek above 0, and a decision deferred to
// the carrier (VerdictDefer) with any Peek, reads the first message
// instead (MaxMessage).
Peek int
// MaxPeek bounds Decision.Need, the prefix of a byte stream that
// VerdictMore may ask for (0: Peek, so that VerdictMore is
// VerdictClose). It is not below Peek, or ErrInvalidConfig.
MaxPeek int
// MaxMessage bounds the first message that the decision on a
// message-framed carrier reads: a longer one is closed without a
// decision (Closed in ordinary admission, TooLarge after Defer). Zero is
// MaxRecordSize, the largest zmux record; a host that
// decides on messages of its own sets the largest it accepts. Above
// MaxRecordSize it is ErrInvalidConfig.
MaxMessage 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, an HTTP request carrier and a deferred
// HTTP upgrade 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 (at most MaxMessage bytes). 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 with CarrierInfo.Framing). An HTTP request carrier is decided on its request head (CarrierInfo.Stage StageHead); on an upgrade's head VerdictDefer decides again on the carrier's first message or bytes once the upgrade completed (CarrierInfo.Upgrade).
The fields are read by NewListener; an Admission must not be changed or copied afterwards.
type AdmissionStage ¶ added in v1.5.5
type AdmissionStage uint8
AdmissionStage is what of a carrier a decision is taken on (CarrierInfo.Stage).
const ( // StageCarrier is the carrier's start: the prefix is its first bytes // (Peek, VerdictMore) or its first message. StageCarrier AdmissionStage = iota // StageHead is an HTTP request's head, before any body byte is read // or the upgrade is answered: 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. StageHead )
type AdmissionStats ¶ added in v1.3.2
type AdmissionStats struct {
Accepted uint64 // VerdictAccept
// Fallback counts carriers handed to a fallback target.
Fallback uint64
// Takeover counts VerdictTakeover at entry to the host callback.
Takeover uint64
// Stalled counts carriers admitted to a stall, including Takeover
// without a byte-stream target.
Stalled uint64
// Closed counts VerdictClose, a decision that panicked, was cancelled,
// or had a Skip outside the prefix or an unknown verdict. It also
// counts prepared takeovers closed before delivery.
Closed uint64
// StallOverflow counts stall attempts closed because they could not
// acquire or commit a stall slot.
StallOverflow uint64
// TooLarge counts oversized first messages after Defer.
TooLarge uint64
// PeekTimedOut counts carriers whose admission ended on expiry.
PeekTimedOut uint64
// HandshakeFailed counts carriers whose outer handshake failed or
// timed out, including a request whose accepted response could not be committed.
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. 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 selects the carrier's normal non-zmux handling. // An HTTP request goes to the adapter's Next handler with its headers // and complete streaming body, or receives HTTP 404 when Next is nil. // Byte streams and message-framed carriers, including QUIC first streams // and already upgraded connections, go to ListenerConfig.Fallback with // the prefix replayed and Decision.Value. Without that target they stall. 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 a request head is VerdictClose. VerdictMore // VerdictDefer completes an HTTP upgrade whose head is being decided // (CarrierInfo.Upgrade, Stage StageHead) and decides again on the // carrier: Decide is called with the same metadata at StageCarrier and // the carrier's first message, or its first Peek bytes (the first // stream of a WebTransport session). PeekTimeout runs on from the // head's decision, and the carrier keeps its slots throughout. On any // other decision it is VerdictClose. VerdictDefer // VerdictTakeover hands the carrier itself to ListenerConfig.Fallback. // HTTP adapters commit the carrier response before the handoff. With // no byte-stream target the carrier stalls. VerdictTakeover )
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
Admit runs the listener's admission on p, the first carrier of the arrival, for an adapter that must know the outcome before it hands further carriers on (a QUIC connection, a WebTransport session): on VerdictAccept it returns p without the skipped bytes and true, to be handed on with HandlePipe or Take. Otherwise it has acted on the verdict and returns false: VerdictFallback hands p, with every byte or message read replayed, to ListenerConfig.Fallback (without one the carrier is stalled) and returns once the fallback did (Detached reports whether the host kept the carrier), VerdictStall stalls it and VerdictClose closes it. Without an Admission, or once the arrival is accepted, it returns p and true. HandlePipe runs admission and setup in one call.
func (*Arrival) AdmitFirst ¶ added in v1.5.5
func (a *Arrival) AdmitFirst(ctx context.Context, first func(context.Context) (PipeIO, error)) (PipeIO, bool)
AdmitFirst is Admit for an adapter whose first carrier comes after the arrival's head decision (an HTTP upgrade): first completes the upgrade or waits for the carrier (the first stream of a WebTransport session) and returns it, within the effective HandshakeTimeout. While the decision is deferred (VerdictDefer) first runs under a context that also ends at the decision's PeekTimeout and when the listener stops taking carriers; a carrier that does not come in time is counted (AdmissionStats.PeekTimedOut, or Closed on the listener's stop). An error of first otherwise is the failure of the arrival's outer handshake (HandshakeFailed), unless ctx ended. On an error first returns no carrier: it closes what it upgraded, and the arrival is released. The carrier then passes the admission as with Admit: on VerdictAccept, and when the head was accepted already, AdmitFirst returns it and true, to be handed on with HandlePipe.
func (*Arrival) Admitted ¶ added in v1.3.2
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
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 without an Admission, on VerdictAccept, or on VerdictTakeover when the listener has a byte-stream target.
func (*Arrival) Detached ¶ added in v1.5.5
Detached reports whether the host detached the carrier of the arrival that Admit, AdmitFirst or HandlePipe handed to ListenerConfig.Fallback (Takeover.Detach): the adapter then leaves the carrier, and what it runs on, to the host. An adapter whose carrier lives only as long as a call of its own (an HTTP handler serving an HTTP/2 stream or a request carrier) keeps that call until the host closed the carrier.
func (*Arrival) HandlePipe ¶ added in v1.3.2
HandlePipe takes ownership of p and returns after handoff or refusal, with the same setup-only context as Listener.HandlePipe. The first carrier passes the listener's admission (unless it was accepted already; one whose decision AdmitUpgrade deferred is decided here, on its first message or bytes, although AdmitFirst is the upgrade adapters' entry, which also bounds the wait for that carrier): its outer TLS handshake is completed, its prefix read and the decision taken, and VerdictFallback hands it 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) PrepareCarrier ¶ added in v1.5.7
func (a *Arrival) PrepareCarrier(ctx context.Context, prepare func(context.Context) error) (err error)
PrepareCarrier runs an adapter's pre-handoff operation while the arrival still accounts for its work. Its context ends on listener stop, parent cancellation, or the earlier of the handshake and deferred peek deadlines.
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) SetupContext ¶ added in v1.5.7
func (a *Arrival) SetupContext(parent context.Context) (ctx context.Context, unlink context.CancelFunc)
SetupContext bounds an adapter's work before it hands off a carrier. It ends with parent or when the listener stops setup. Call unlink when setup has finished so the established carrier has its own lifetime.
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 has stopped setup, 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 completes setup and waits for the attached pipe or lane to end, even when setup failed after attachment. Its context bounds setup only. Take serves an adapter that answers a carrier's request according to whether the listener took it (the exchange carrier).
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.
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;
// pipes it returns with an error are aborted.
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
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*RecoveryRatio. A zero Rate turns it off, so the zero CapacityFloor reports nothing. A zero RecoveryRatio means DefaultRecoveryRatio, 1.25 (1 is no hysteresis); any other must be a finite number of at least 1 (a smaller one would restore below the floor, an infinite one never), else SetCapacityFloor returns ErrInvalidConfig.
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 CarrierCounts ¶ added in v1.5.7
type CarrierCounts struct {
TCPSegments *TCPSegmentCounters
TCPPackets *TCPPacketCounters
QUIC *QUICCounters
}
CarrierCounts contains one native pair, or all nil when unavailable.
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 CarrierDirection ¶ added in v1.5.7
type CarrierDirection = carrierstats.Direction
CarrierDirection identifies the sampled sender relative to the local process.
type CarrierID ¶ added in v1.5.7
type CarrierID = carrierstats.CarrierID
CarrierID is an opaque, process-local connection identity. Its zero value is invalid.
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
// Stage is what of the carrier the decision is taken on: its request
// head (StageHead) or its start (StageCarrier, the zero value).
Stage AdmissionStage
// Framing is the carrier's framing at StageCarrier (the prefix is the
// start of a byte stream, or a first message with FramingRecords), as
// admit.ClassifyFirstBytes takes it; zero on a head.
Framing Framing
// Upgrade marks the carrier of an HTTP upgrade (WebSocket,
// WebTransport; ListenerAdapter.AdmitUpgrade), on its head and on the
// decision a VerdictDefer on that head takes on the carrier.
Upgrade 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 CarrierSample ¶ added in v1.5.7
type CarrierSample struct {
CarrierID CarrierID
Generation uint64
Direction CarrierDirection
Source CarrierSource
SampledAt time.Time
Counts CarrierCounts
}
CarrierSample reports an observation of the local sender across all pipes and sessions sharing one connection. A reset advances Generation.
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 CarrierSource ¶ added in v1.5.7
type CarrierSource = carrierstats.Source
CarrierSource identifies a native provider and its counter semantics.
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.
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.
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 or HandleUniStreams; 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
// DatagramQueueDelay is the target queueing delay of every datagram
// queue (the send queue, the session receive queue and each stream's):
// once the datagrams leaving a queue have waited longer than it for
// 100 ms, CoDel (RFC 8289) drops some as they leave, more the longer
// the standing delay lasts, each counted as dropped; a datagram alone
// in its queue is never dropped for its delay. The count and byte
// bounds stay as memory bounds. Zero is 20 ms; a negative value turns
// the delay bound off.
DatagramQueueDelay time.Duration
// 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 SendBufferMax.
SendBuffer int64
// SendBufferMax 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.
SendBufferMax 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
// DefaultMaxLanes (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
// JoinOutcome reports each authorized incoming join and each outgoing
// carrier exactly once. A nil error means peer attachment. Calls can
// overlap and run outside session locks on goroutines independent of
// Conn.Wait. NextEvent and HandleEvents release a successful pipe's
// events after its hook returns. Tracer may deliver earlier and drop
// events. A hook can close and wait for its session. Draining its own
// held event keys requires returning from the hook first.
JoinOutcome func(c *Conn, pipe PipeID, err error)
// 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 TryAcquire(n, n) grants its payload of n bytes (refunded
// when it is then not queued); otherwise it is dropped and counted.
DatagramLimiter DatagramLimiter
// Tracer receives session events on a goroutine of its own, through a
// backlog of 256 events per session that is not configurable.
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), and the pool
// policy decisions rejected without a DecisionRejected callback. 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 and 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.
// A host can explicitly request one advised replacement with
// Conn.RequestPipeReplacement. It uses the same callback with its
// own backoff history. An outage cancels a pending replacement and
// can call Redial and RedialPolicy while the replacement unwinds.
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
// Decide that returns an error or panics, or 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 error of each look 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. Unset, the error
// is logged to Logger. Redialling goes on either way.
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.
type Conn ¶
type Conn struct {
// contains filtered or unexported fields
}
Conn is a zmux session. Its methods are safe for concurrent use.
A session is not closed by the garbage collector: like a net.Conn it holds its carriers, goroutines and timers until Close (or CloseWithError, Shutdown or the peer's close) ends it, so every session must be closed, also when its streams are all done.
Concurrency model: one mutex guards the sans-IO core; no I/O or blocking runs under it. Each inbound lane has a reader. Each outbound lane starts a writer on demand and keeps it for writerIdle after an empty poll. A lane wake signals its parked writer under the lock or reserves a new writer to launch after unlock.
func Client ¶
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
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 ¶
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
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 ¶
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
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
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) CapacityFloor ¶ added in v1.5.0
func (c *Conn) CapacityFloor() CapacityFloor
CapacityFloor returns the capacity floor of the outbound direction, the zero CapacityFloor when none is set. It does not fail or wait.
func (*Conn) Close ¶
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; a reason over 1024 bytes is cut at a UTF-8 character boundary). 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
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
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) ExportKeyingMaterial ¶ added in v1.3.3
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) HandleEvents ¶ added in v1.5.7
HandleEvents exclusively consumes NextEvent's keyed queue. It calls f serially, removing one event immediately before each call. A panic consumes that event and delivery continues. After close, buffered events can still be claimed and drained. Once the frozen queue is empty, a first registration returns the terminal error. Repeated registration and blocked or later NextEvent calls return ErrHandlerRegistered. Wait does not wait for f.
func (*Conn) HandleStreams ¶ added in v1.5.7
HandleStreams assigns queued and future peer bidirectional streams to f in accept order. Each call runs in its own goroutine, with at most maxConcurrent calls outstanding. The callback owns its stream and may retain it after return. A panic cancels both directions with StreamCancelled. Registration is permanent and excludes AcceptStream. Repeated registration and blocked or later AcceptStream calls return ErrHandlerRegistered. Wait does not wait for callbacks.
func (*Conn) HandleUniStreams ¶ added in v1.5.7
func (c *Conn) HandleUniStreams(f func(*ReceiveStream), maxConcurrent int) error
HandleUniStreams is HandleStreams for incoming unidirectional streams. It activates staged uni credit as AcceptUniStream does and excludes that method. A panic cancels the read direction with StreamCancelled.
func (*Conn) ID ¶ added in v1.4.10
ID is the session's identity within the process, as a Tracer is given it.
func (*Conn) Liveness ¶ added in v1.3.3
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 and a DeadTimeout that is off included), and a derived DeadTimeout is zero, so that SetLiveness with the result changes nothing.
func (*Conn) LocalAddr ¶ added in v1.3.0
LocalAddr returns the local address of pipe 0 when its carrier has one.
func (*Conn) MaintainPipes ¶ added in v1.3.0
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
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 keyed queue: at most one unread event per key (a pipe's state of one direction, a tier, a carrier candidate, a kind of session event), which a new occurrence of the key updates and moves to the tail, so events are read in the order of their keys' latest occurrences and the last one read of a key is its latest state. The queue never drops an event and needs no bound of its own: its keys are those of the pipes, tiers and candidates the session holds, and a retired pipe's keys leave it for EventPipesRetired. Reading it is optional. Once the session has ended nothing more enters it. It is independent of Config.Tracer, which receives every occurrence, on its own backlog, whether or not NextEvent is called. Concurrent callers each receive different events. Calling NextEvent enables path quality advice until StopEvents.
func (*Conn) OpenPipeStream ¶ added in v1.3.0
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 ¶
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
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 ¶
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
Pipe returns the handle of attachment id while the session knows it.
func (*Conn) PipeStats ¶ added in v1.3.0
PipeStats returns a snapshot of every attachment. A session without multipath reports pipe 0.
func (*Conn) Pipes ¶ added in v1.3.0
Pipes returns the handles of the session's current attachments. A session without multipath has pipe 0.
func (*Conn) QualityBand ¶ added in v1.5.0
func (c *Conn) QualityBand() QualityBand
QualityBand returns the default band of the session's pipes, the zero QualityBand when none is set. It does not fail or wait.
func (*Conn) RaiseIncomingStreams ¶ added in v1.3.3
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 or HandleUniStreams 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
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
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
RemoteAddr returns the remote address of pipe 0 when its carrier has one.
func (*Conn) ReplacePipes ¶ added in v1.4.5
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) RequestPipeReplacement ¶ added in v1.5.7
RequestPipeReplacement asks the configured Redial hook to try an advised replacement. The host calls this after reviewing EventPipePathQuality. Calls for the current episode coalesce. An outstanding request can finish or expire before the host submits a request for another pipe.
func (*Conn) RevalidatePipes ¶ added in v1.3.0
RevalidatePipes revalidates every live outbound pipe (after a network change).
func (*Conn) Scheduler ¶ added in v1.5.0
Scheduler returns the session's scheduling policy: never nil, the configured one until SetScheduler changes it. It does not fail or wait, and answers on a closed session with the value it held last.
func (*Conn) SendDatagram ¶ added in v1.3.0
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
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
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) error
SetCapacityFloor sets the capacity floor of the outbound direction; a RecoveryRatio that is not valid (see CapacityFloor) is ErrInvalidConfig, as in a QualityBand.
func (*Conn) SetJoinSecret ¶ added in v1.3.3
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
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
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; the zero QualityBand clears it.
func (*Conn) SetScheduler ¶ added in v1.3.0
SetScheduler changes the session's scheduling policy; it applies from the next chunk. The session always has one: nil sets the default, SchedulerAffinity. Streams that follow the session (Stream.SetScheduler with nil) take the new policy too.
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
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
ShapingLimits returns the session's shaping limits.
func (*Conn) ShapingMeters ¶ added in v1.4.0
ShapingMeters returns the session's shaping readings.
func (*Conn) ShapingStats ¶ added in v1.3.2
ShapingStats returns the shaping counters.
func (*Conn) Shutdown ¶ added in v1.3.0
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) StopEvents ¶ added in v1.5.7
StopEvents unregisters HandleEvents and releases the advice subscription established by NextEvent. A dispatched callback may finish, and the keyed queue remains available. A new NextEvent or HandleEvents call subscribes again. Independently configured Redial and Tracer callbacks keep receiving advice.
func (*Conn) Wait ¶
Wait returns the session's error after the session closes, its tracked workers exit, and each pipe's inbound side ends or the linger timeout expires. After CloseWithError, a return before the linger timeout confirms that the peer read CONNECTION_CLOSE. Done is the selectable form of Wait.
Host hooks (Tracer, Pick, AllowConnectionWindowIncrease) and callbacks registered with HandleStreams, HandleUniStreams, or HandleEvents may call Wait. These callbacks may still be running or start after Wait returns.
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
// PathDatagramPayload is the largest session datagram payload that
// leaves as one datagram of the carrier (a QUIC DATAGRAM, its size as
// the carrier last reported it, path MTU discovery included) instead
// of in a record; on a carrier without datagrams it is
// MaxDatagramPayload, since every datagram rides the records there.
// Stream.PathDatagramPayload gives the one of a stream;
// EventDatagramPathChanged reports changes.
PathDatagramPayload 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
// LogLinesDropped counts the warnings not delivered to Config.Logger
// because the session's queue of 256 lines was full (the Logger blocked
// or slow); it is not configurable.
LogLinesDropped 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)
// Stream gap counters and total completed wait, enabled by Tracer.StreamEvents.
StreamGapsStarted, StreamGapsFilled uint64
StreamGapWait time.Duration
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 is a gauge of 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 is called
// by the pipe's channel goroutine, outside the session's lock, before
// each round of channel datagrams; the session places datagrams by the
// last answer until the next.
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 outside the session's lock, by the pipe's channel
// goroutine when the pipe attaches; the pipe's first record waits for
// it, so it must return promptly. A panic in it fails the pipe.
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 or one it takes
// over (VerdictAccept, VerdictFallback or VerdictTakeover): zmux
// hands it on without looking at it, on VerdictAccept to WrapPipe
// (PipeHint.Admitted) and to the session (AdmittedAs) or pipe
// (AdmittedAs) the carrier makes, holding it until their state is
// released, and on stream handoff to ListenerConfig.Fallback
// (Takeover.Value), where it routes the carrier: a listener has one
// Fallback, and the Value says which of the host's services the
// carrier goes to. 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 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
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
func (e *EarlyDataRejectedError) Is(t error) bool
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.
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
// PathQuality is the reason for EventPipePathQuality.
PathQuality PipePathQualityReason
// Epoch of EventEpochCommitted and EventEpochDeleted.
Epoch uint64
// Count of EventJoinAuthFailed: the failures with its Reason since the
// event was last read, at least 1 (a Tracer gets one event per
// failure, with Count 1).
Count 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
// Stream events are opt-in through Tracer.StreamEvents. Offsets and
// lengths are wire bytes, including any preamble. StreamLength is
// set for placements. StreamAt is the event time on the session clock.
StreamID StreamID
StreamOffset, StreamLength uint64
StreamAt time.Time
GapWait time.Duration
// Priority is the tier (EventPipePriorityChanged,
// EventTierSaturation); Weight the pipe's weight
// (EventPipePriorityChanged); Source where the priority comes from, as
// PipeStats.SendPrioritySource says: "local" (a setting of this
// endpoint), "peer" (the peer's request) or "default".
Priority uint64
Weight uint64
Source string
// 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; 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. A Tracer gets
// one event per retired pipe (Retired 1, Last that pipe, Failed 1 if
// the pipe failed, else Closed 1).
Retired, Failed, Closed uint64
Last []PipeID
// DatagramPayload of EventDatagramPathChanged: the new
// PathDatagramPayload of a session datagram.
DatagramPayload int
// FateGroup and QueuedBytes are set for EventPipePathQuality,
// together with the recent SmoothedRTT and DeliveryRate estimates.
// RetryAfter is a replacement delay suggestion; zero means no redial.
FateGroup, QueuedBytes uint64
RetryAfter time.Duration
}
Event is a session event, as NextEvent and Tracer.Event report it. Kind says which of the other fields are set (see EventKind). Stream events are delivered through Tracer.Event when Tracer.StreamEvents is enabled.
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, // Source). EventPipePriorityChanged // EventTierSaturation reports that the usable pipes of a tier became // saturated or stopped being so (Priority, Saturated). EventTierSaturation // EventJoinAuthFailed reports that joins failed authentication for a // Reason (Reason, Count: the failures of that reason since the event // was last read). 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. An unread // one leaves the queue when EventSessionResumed occurs. 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, 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 // EventDatagramPathChanged reports a new ConnectionState. // PathDatagramPayload (DatagramPayload): the carrier's datagram size // changed (path MTU discovery), another pipe carries the datagrams, or // they moved between the carrier's datagrams and records. It is // noticed when the session sends or its pipes change. EventDatagramPathChanged // EventStreamPlaced reports a STREAM range handed to a multipath // carrier, including copies and retransmissions. EventStreamPlaced // EventStreamGapStarted reports the leading missing offset. PipeID is // the pipe of the arriving STREAM that exposed the gap. EventStreamGapStarted // EventStreamGapFilled reports that the leading missing byte arrived. // PipeID is the pipe of that arrival and GapWait is the elapsed time. EventStreamGapFilled // EventPipePathQuality reports evidence for local replacement or shared // path deterioration, and when the observed deterioration clears. EventPipePathQuality )
type FailureReporter ¶ added in v1.5.5
type FailureReporter interface{ ReportsFailure() bool }
FailureReporter is a half whose carrier reports its own failure: ReportsFailure true means that when the path under the carrier fails, its reads or writes fail (an error, a reset, an unexpected end), as a stream of an outer zmux session does when that session's liveness ends it (StreamPipe, Conn.OpenPipeStream). The carrier reports it only when every half does: a split carrier with one plain half (a raw connection, which can stall silently) keeps stall detection. Stall detection then never fails the pipe: a carrier queued behind a rate limit stalls without being dead, and its own end is the failure signal. The pipe still turns suspect and is avoided and probed while it stalls. An explicit PipeLiveness.DeadTimeout of the pipe overrides it.
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
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 {
PositionSentKnown, PositionAckedKnown, PositionReceivedKnown bool
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. The Known flags distinguish a zero position from an unavailable position.
type Limiter ¶ added in v1.3.0
type Limiter interface {
// Acquire waits until it can grant. When ctx ends it returns the
// cancellation and nothing is taken in net; an error takes nothing
// and fails the operation that asked.
Acquire(ctx context.Context, minBytes, maxBytes int64) (int64, error)
// TryAcquire grants without blocking, or returns 0 with the reason
// and nothing taken.
TryAcquire(minBytes, maxBytes int64) (int64, error)
// Refund gives back n granted bytes that were not used. It is
// best-effort, never blocks and is called from any goroutine; n <= 0
// does nothing.
Refund(n int64)
}
Limiter lets an external limiter, budget or meter act on bytes that zmux forwards itself (Splice, SplicePackets, datagrams). The model is reserve, then refund: zmux takes bytes before it moves them and gives back what it did not use. Units are bytes.
Arguments: maxBytes <= 0 takes nothing and returns 0 at once; minBytes < 1 is taken as 1; minBytes > maxBytes as minBytes = maxBytes. (n, n) is therefore an all-or-nothing request and (1, max) a request for as much as possible. A grant n satisfies min' <= n <= maxBytes, where min' is minBytes, or less when the limiter can never allow minBytes at once (its burst). For an atomic unit requested as (n, n), a successful grant lets the whole unit pass, even when fewer bytes were returned.
Every method is safe for concurrent use. zmux calls them outside every session lock, never from inside the session core, and never while it holds a buffer of its own in Acquire.
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 locks are leaves: none 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) 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
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 accepted continue, without new pipes from the listener (Shutdown ends them), and those still waiting for Accept are aborted.
func (*Listener) Drain ¶ added in v1.5.7
Drain refuses subsequent bootstrap handshakes with CONNECTION_REFUSED and msg. Existing sessions can still join, add lanes, and resume.
func (*Listener) HandlePipe ¶ added in v1.3.0
HandlePipe takes ownership of p on entry. The caller must never close p, including when HandlePipe returns an error. It returns when the carrier has started or joined a session, has been refused, or Fallback has returned on the caller's goroutine. ctx bounds admission, classification and setup through handoff. Once attached, the session drives the close, including CONNECTION_CLOSE after a handshake failure or policy refusal. A nil result means bootstrap entered the backlog, a join was confirmed, or a lane was attached, or Fallback returned normally. Once committed, the setup result survives cancellation even before HandlePipe returns. I/O can outlive an error return, and later carrier failures are reported by the session.
Classification uses the first record or the hint. 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) Limits ¶ added in v1.5.6
func (l *Listener) Limits() ListenerLimits
Limits returns the limits in effect, defaults filled in: a zero count or timeout reads as its default, no timeout as -1, unlimited MaxPending as -1, so that a changed copy keeps the others' meaning.
func (*Listener) Serve ¶ added in v1.3.0
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 new carriers are refused. 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). Each carrier goroutine returns after HandlePipe decides its fate. Cancelling ctx stops pending setup. Established pipes remain with their sessions.
func (*Listener) SetLimits ¶ added in v1.5.6
func (l *Listener) SetLimits(lim ListenerLimits) error
SetLimits replaces the listener's limits; invalid limits change nothing and return an error wrapping ErrInvalidConfig. New carriers and the next decisions on held ones use them at once: lowered pending bounds refuse or displace new carriers until the count is below them, but close no carrier already held; a lowered MaxPendingPerSession applies to the next join of a session; a lowered MaxSuspended closes the longest-suspended sessions beyond it with ZMUX_RESUME_TIMEOUT; a changed FirstRecordTimeout applies to carriers that arrive after the call; a changed MemoryBudget starts or ends memory pressure at once, as if the charged sum had crossed the new bounds (OnMemoryPressure, suspended sessions closed the largest first).
func (*Listener) Shutdown ¶ added in v1.3.0
Shutdown irreversibly drains bootstrap admission and gracefully closes published sessions. Their joins and resumptions can run until 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) Undrain ¶ added in v1.5.7
func (l *Listener) Undrain()
Undrain resumes bootstrap admission unless shutdown has started.
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, Takeover, Stalled + StallOverflow and Closed + TooLarge, respectively. Takeover is recorded as the carrier enters the host callback. 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. A configured HTTP fallback receives the original request with that prefix and the unread body, before any carrier response. A nil HTTP fallback serves http.NotFound. VerdictTakeover selects the byte-stream target after the adapter commits the accepted response.
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.Stage is StageHead and Upgrade 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), on VerdictTakeover with a byte-stream target, and on VerdictDefer, which defers the decision to the carrier, it returns the arrival and true: the caller completes the upgrade and takes its first carrier through Arrival.AdmitFirst, which also takes a deferred decision, and hands it on with Arrival.HandlePipe. 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. NewListener
// takes a shallow copy and validates it for server sessions. Its
// HandshakeTimeout also bounds the wait for a 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,
// WrapPipe, Fallback) and
// the errors SessionConfig returns;
// nil logs nothing. The sessions log to their Config.Logger.
Logger *slog.Logger
// ListenerLimits are the bounds SetLimits changes while the listener
// runs; these are their initial values.
ListenerLimits
// 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
// 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. It is called
// synchronously on the carrier's goroutine, under no deadline of its
// own: it must return promptly, well within the peer's handshake or
// join timeout.
OnReject func(RejectInfo) RejectAction
// 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 is the listener's byte-stream and message-carrier target.
// VerdictTakeover selects it on every transport. VerdictFallback selects
// it for TCP/TLS, QUIC first streams and already upgraded WebSocket or
// WebTransport carriers. While the carrier is an HTTP request,
// VerdictFallback serves Options.Next or responds with HTTP 404.
// A carrier directed here stalls if Fallback is nil.
//
// The host receives the inspected prefix replayed and can route by
// Takeover.Value. For message framing the replay is a whole non-empty
// first message. The callback runs on the carrier's setup goroutine
// after its slots are returned. Its context ends when it returns.
// Returning closes the carrier unless the host called Takeover.Detach,
// in which case the host owns it and closes it once done.
Fallback func(ctx context.Context, t *Takeover)
// 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). It is called synchronously
// before the session and its handshake timer exist, under no deadline
// of its own (ctx is HandlePipe's): it must return well before the
// peer's handshake deadline, which keeps running meanwhile.
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 ListenerLimits ¶ added in v1.5.6
type ListenerLimits struct {
// 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
// MaxPendingPerSession bounds the Unconfirmed carriers of one session:
// joins that passed authentication and wait for the joiner's
// confirmation (a join in Bound Mode is confirmed by its verification
// and holds no place). Zero is 4. A new authenticated Hello is never
// refused for lack of room: once the bound is reached, the carrier
// that has been Unconfirmed longest is closed first, as a failed join;
// below it, none is.
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
// 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
}
ListenerLimits are the bounds of a Listener that SetLimits changes while it runs; ListenerConfig embeds them for their initial values.
The other settings are fixed for the listener's life: Backlog (the capacity of the accept queue), SourcePrefixV4 and SourcePrefixV6 (they key the slots live carriers hold), InstanceID, the callbacks and Config, whose HandshakeTimeout bounds the carriers. The bounds of a session itself are its Config: SessionConfig, called for every new session, returns the Config current at the time; an established session keeps the Config it started with.
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, and an Unconfirmed carrier
// closed to make room for a newer join, which counts here and in
// Joins only if it was Confirmed), 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; a negative
// value turns stall-based failure off: a stalled pipe still turns
// suspect, is avoided by the scheduler, has its data reinjected and is
// probed, but only its carrier's error or end, its drain deadline or
// its removal fail it (and the inbound silence of a receive-only pipe
// that is not the last one); otherwise at least 1 s, and any larger
// value is safe (deadlines saturate). A pipe whose carrier reports its
// own failure (FailureReporter, such as StreamPipe) has it off unless
// its own PipeLiveness.DeadTimeout is set.
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
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 MessageReader ¶ added in v1.3.0
type MessageReader interface {
// ReadMessage returns the next whole 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). limit is always positive: zmux never asks
// for more than MaxRecordSize, and the admission of a listener asks for
// its peek (Admission.Peek, MaxPeek). The caller owns the returned
// slice.
ReadMessage(limit int) ([]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 NetConner ¶ added in v1.5.5
NetConner is a half over a connection that it names: the connection below it, as a TLS connection's NetConn. The listener measures the TCP socket under a half through it (Unsent).
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
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
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
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
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
Abort removes the pipe abruptly: failure, reinjection and PIPE_ABANDON(ZMUX_PIPE_FAILED). It takes no code and no cause: the wire code is fixed and the caller knows why it aborted; Wait reports ErrPipeAborted.
func (*Pipe) Close ¶ added in v1.3.0
Close removes the pipe gracefully with PIPE_ABANDON(NO_ERROR) and drain. A join that is still waiting for peer confirmation closes its carrier without sending PIPE_ABANDON. Close does not block. NextEvent reports the pipe's end.
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) Options ¶ added in v1.5.0
func (p *Pipe) Options() PipeOptions
Options returns the pipe's options: those given at AddPipe with every Update applied, each as the pipe holds it. A field that follows the session or the peer (a Change that was never set, or was cleared) reads as the zero Change, not as the value in force, which PipeStats reports. The fields fixed when the pipe was created read the values it has: Direction (from this endpoint's view), RecordMode (the mode chosen, also when Config.RecordPolicy chose it), KeyGroup (the group of its Join, also when AddPipe left it zero), FateGroup and Label. ReturnOnReply is what AddPipe was given, so options read back and handed to the AddPipe of a replacing pipe behave alike. It does not fail or wait, and once the pipe is gone it returns the options the pipe last held. A pipe that this endpoint's AddPipe did not add (the bootstrap pipe, one the peer joined) holds the defaults, Label empty and ReturnOnReply false, but for Direction, RecordMode and KeyGroup, which are those of its Join, until an Update sets a field.
func (*Pipe) Revalidate ¶ added in v1.3.0
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
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
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, ErrPipeAborted for one this endpoint aborted, the cause for a failed 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
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.
const UnassignedPipeID PipeID = 1 << 62
UnassignedPipeID identifies an outbound JoinOutcome whose setup failed before the protocol allocated a pipe ID. It is outside the wire ID space.
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
// MaxRecord is the largest record plaintext zmux writes on the carrier,
// a local bound applied beside the peer's max_record_size and never
// negotiated; 0: the carrier's default. A half implementing
// CarrierRecordLimit lowers it further (the smaller bound holds). It
// applies to the first pipe and to added pipes alike. It has a floor
// but no upper bound: a value below MinMaxRecord other than 0 is
// ErrInvalidConfig where the PipeIO is used, as for WriteOverhead; any
// larger value is a cap that the peer's max_record_size and the
// implementation's own record limit (MaxRecordSize) reduce further.
MaxRecord 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
// contains filtered or unexported fields
}
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);
A half's Close must interrupt a blocked Read or Write.
func NetPipe ¶ added in v1.3.0
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
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
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
func SealRecords(p PipeIO, s RecordSealer, o RecordOpener, mode RecordMode, exp KeyingMaterialExporter) PipeIO
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. It does not check the carrier's record limit against the Sealed floor: CheckSealedCarrier does, before the handshake.
func SecureTLS ¶ added in v1.4.0
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
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; a negative value turns stall-based
// failure of the pipe off, as for Liveness.DeadTimeout. Zero follows
// the carrier (off when it reports its own failure, FailureReporter),
// else the session's; a nonzero value overrides both.
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).
// Set(QualityBand{}) turns the pipe's reports off whatever the
// session's band is (the zero band is both halves off). 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 PipePathQualityReason ¶ added in v1.5.7
type PipePathQualityReason uint8
PipePathQualityReason is the evidence for EventPipePathQuality.
type PipePool ¶ added in v1.3.0
type PipePool struct {
// Policy, when set, is asked on every pass of the pool: on a pipe or
// session event, after each dial attempt, at its Recheck and every
// 100 ms. Its DialAfter replaces the backoff, bounded by Backoff.Max,
// and its Liveness applies to the pipes dialled after it. A Decide
// that returns an error or panics, or a decision that fails
// PoolDecision.Validate, is rejected: the pass goes on as with the zero decision and the error
// is reported to DecisionRejected, else logged to Config.Logger.
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. Pipes it
// returns with an error are aborted.
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 error of each look 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. Unset, the error is logged to
// Config.Logger. The pool goes on maintaining its pipes either way.
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 {
// Epoch is the epoch the pipe joined in, when EpochKnown is true.
Epoch uint64
// ReplaceBy is the scheduled make-before-break replacement time.
// It is zero when no replacement time is scheduled.
ReplaceBy time.Time
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
EpochKnown 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 // gauge: time since attachment
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 // gauge: outbound weight
// 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
// CarrierSample is a detached snapshot of the outbound carrier connection.
CarrierSample *CarrierSample
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 // gauge
SinceLastReceive time.Duration // gauge
// SinceLastTraffic is a gauge of 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 uint64
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, the zero band turning the pipe's reports off; 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 keeps the pool's own behaviour:
// a PipePool keeps its Count (at least one), a carrier.ConnPool dials
// a connection only when a pipe finds none with room. A Count below
// the pool's size, its members and Dialing together, shrinks the pool
// one step at a time: the growth dials under way are cancelled first,
// the most recently started first (a dial on demand is not one, is
// not counted and is never cancelled); then members close, those in
// RetirePipes (RetireConnections) first, then the longest Idle, ties
// broken by the fewest Pipes, the least Age, then the highest key. A
// PipePool member closes gracefully, with its replacement if one is
// being joined. A connection is retired: it takes no new pipe at once,
// no longer counts, is reported with Usable false and closes once its
// last pipe ends (at once when it carries none). 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 leaves the pool's
// backoff in force where it has one (a PipePool or a redial policy) and
// asks for no delay of a carrier.ConnPool, which has none; a negative
// value is invalid.
DialAfter time.Duration
// Recheck asks for the next Decide within this time even when nothing
// else happens; zero asks for none beyond the pool's own looks (its
// events, dials and the maintenance interval of 100 ms), and a
// negative value is invalid. A positive value is lengthened to
// MinRecheck at least, so the shortest recheck is MinRecheck; zero is
// never "at once". It has no upper bound of its own.
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 Decide that returns an error or panics rejects the look: d is then the zero decision and the error is Decide's, or names the panic. Otherwise the error is the decision's Validate error, the decision left as it is. A pool that gets an error rejects the decision and 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 before a pool asks its policy again after d: d's Recheck, raised to MinRecheck, when it comes before the pool's maintenance interval (100 ms), else that interval.
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 ID of the first pipe of a PipePool member, pipe 0
// included; it means nothing for a connection.
PipeID PipeID
// FateGroup is the fate group of a carrier.ConnPool connection, never
// 0; 0 for a PipePool member.
FateGroup uint64
// Age is the time since its oldest pipe was attached, or since the
// connection was established.
Age time.Duration
// Idle: for a member, the least PipeStats.SinceLastTraffic of its
// pipes (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 // its pipes: 1 for a dialled pipe, the group's size for a joined member, the pipes on a connection
BytesSent uint64 // over its pipes; 0 for a connection
BytesReceived uint64 // over its pipes; 0 for a connection
// Usable: every pipe serves its direction and the peer attached it;
// for a connection, it takes new pipes (it is not retired).
Usable bool
// Replacing: a replacement of it is being dialled or joined; always
// false for a connection.
Replacing bool
}
PoolMember is a member of a PipePool (a pipe, or the pipes a Join joined together), or a connection of a carrier.ConnPool. One key identifies it, and a decision names it by that key: a PipePool member by PipeID, a connection by FateGroup. A member is a connection exactly when its FateGroup is non-zero (a carrier pool never gives a connection fate group 0); PipeID cannot tell, since pipe 0 is a pipe.
type PoolPolicy ¶ added in v1.3.2
type PoolPolicy interface {
Decide(v *PoolView, d *PoolDecision) error
}
PoolPolicy decides the members a pool keeps and when it dials. Decide runs on the pool's goroutine, must return promptly and must not block or call into the session. A non-nil error rejects the look: the pool goes on as with the zero decision and reports the error to its DecisionRejected callback, else logs it at warning level (a PipePool to Config.Logger, a carrier.ConnPool to its Logger). A decision with a value out of range is rejected the same way (PoolDecision.Validate), and so is a Decide that panics; no value is corrected into range.
type PoolView ¶ added in v1.3.2
type PoolView struct {
// Members are the pool's members; a replacement being joined is not
// one until it replaces its member.
Members []PoolMember
// Failures counts the consecutive failed dial attempts of the pool
// (redials and replacements alike); 0 once a dial gives a usable
// member.
Failures int
// SinceLastDial is the time since the start of the pool's last dial
// attempt; negative before the first.
SinceLastDial time.Duration
// Dialing counts the pool's own growth dials in progress: the dial
// attempts it started to reach its count (first dials and redials),
// and a replacement whose member has gone meanwhile, which then adds
// one. A replacement of a member still there is not counted, and
// neither is a dial on demand, one a carrier.ConnPool.Get makes because
// no connection has room. A pool that dials inside its looks, so that
// none is in progress when it asks its policy, always reports 0: a
// PipePool (MaintainPipes) does.
Dialing int
}
PoolView is the state of a pool. It holds durations, not points in time, so that a policy reads no clock of its own.
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. It is an argument error: it matches ErrInvalidConfig.
func (*PreambleTooLargeError) Error ¶ added in v1.3.2
func (e *PreambleTooLargeError) Error() string
Error describes the limit.
func (*PreambleTooLargeError) Is ¶ added in v1.5.0
func (e *PreambleTooLargeError) Is(target error) bool
Is matches ErrInvalidConfig.
type QUICCounters ¶ added in v1.5.7
type QUICCounters struct {
PacketsSent, PacketsLost uint64
}
QUICCounters report QUIC sent and lost packets. PacketsLost can decrease when the transport corrects a loss declaration after a late ACK.
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 DefaultMinInterval (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 RTT, or a RateRatio other than 0 or a finite number of at least 1, 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) NotifyReadable ¶ added in v1.5.2
func (s *ReceiveStream) NotifyReadable(f func()) (stop func() bool)
NotifyReadable calls f once the stream is readable, as Stream.NotifyReadable.
func (*ReceiveStream) PeerPriority ¶ added in v1.5.0
func (s *ReceiveStream) PeerPriority() (urgency Urgency, incremental, ok bool)
PeerPriority returns the priority requested for the peer's sending part, as Stream.PeerPriority.
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) ReceiveWindow ¶ added in v1.5.0
func (s *ReceiveStream) ReceiveWindow() (initial, limit uint64)
ReceiveWindow returns the stream's receive window, as Stream.ReceiveWindow.
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) error
SetReceiveWindow sets the stream's initial and maximum receive window, as Stream.SetReceiveWindow.
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) TryRead ¶ added in v1.5.0
func (s *ReceiveStream) TryRead(p []byte) (int, error)
TryRead reads what is readable now without waiting, as Stream.TryRead.
func (*ReceiveStream) WaitReadable ¶ added in v1.5.0
func (s *ReceiveStream) WaitReadable(ctx context.Context) error
WaitReadable waits until a Read would not block, as Stream.WaitReadable.
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 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.
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)
srv := make(chan *zmux.Conn, 1)
go func() {
s, err := zmux.Server(ctx, b, scfg)
srv <- s
ch <- err
}()
client, err = zmux.Client(ctx, a, ccfg)
server = <-srv
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
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 estimates arrival per chunk. It spreads to a later pipe when the stream's ready backlog can hide the delay and receive credit can hold the reordering.
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; explicit sizes are from 1 to 2^31 - 1.
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) Priority ¶ added in v1.5.0
func (s *SendStream) Priority() (urgency Urgency, incremental bool)
Priority returns the local scheduling priority, as Stream.Priority.
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) Redundant ¶ added in v1.5.0
func (s *SendStream) Redundant() (on, set bool)
Redundant returns what SetRedundant set, as Stream.Redundant.
func (*SendStream) Scheduler ¶ added in v1.5.0
func (s *SendStream) Scheduler() Scheduler
Scheduler returns the stream's own scheduling policy, as Stream.Scheduler.
func (*SendStream) SendBuffer ¶ added in v1.5.0
func (s *SendStream) SendBuffer() int
SendBuffer returns the bound of the stream's written-but-unreleased bytes, as Stream.SendBuffer.
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 makes it follow the session's again.
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) TryWrite ¶ added in v1.4.10
func (s *SendStream) TryWrite(p []byte) (int, error)
TryWrite writes the prefix of p that fits now, as Stream.TryWrite.
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
WaitSendCapacity waits for send capacity (see Stream.WaitSendCapacity).
func (*SendStream) WaitWritable ¶ added in v1.4.10
func (s *SendStream) WaitWritable(ctx context.Context) (uint64, error)
WaitWritable waits for room for a write (see Stream.WaitWritable).
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 SessionError ¶ added in v1.5.7
type SessionError = TransportError
SessionError is the transport close reported by a session. ErrorMessage contains the peer's reason, including the reason supplied to Listener.Drain.
type SessionID ¶ added in v1.4.10
type SessionID uint64
SessionID is a session's identity within the process: distinct for every session the process makes (a counter from 1, never reused), so that hooks shared by the sessions of one Config, such as a Tracer, tell them apart. It is the "zmux.session" goroutine label. It is not sent to the peer.
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 were dropped for their size and DatagramsLimited
// were refused by the direction's Limiter or the next session's send
// limiter. Splice drops for its size a datagram larger than the next
// hop's MaxDatagramPayload. SplicePackets forwards such a datagram as
// a capsule instead (DatagramsAsCapsules) and drops for its size only
// one larger than DefaultMaxPacket; a capsule it could not write for
// another reason (the downstream stream ended or was reset, the splice
// ended) counts in DatagramsDropped alone, as does a datagram whose next
// session does not use stream datagrams.
DatagramsDropped, DatagramsTooLarge, DatagramsLimited uint64
// DatagramsAsCapsules counts the datagrams SplicePackets forwarded
// as DATAGRAM capsules on the stream, once written whole (their
// payload is in DatagramBytes); 0 for Splice.
DatagramsAsCapsules 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, that of the context's cause for SpliceCancelled (ZMUX_CANCELLED, the code of the reset, for a plain cancel or a deadline), and 0 for the other kinds. SpliceLimiterFailed resets the downstream and stops the upstream with ZMUX_CANCELLED; the other direction goes on.
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, with Code SpliceLimiterFailed // the direction's Limiter failed in Acquire )
The events that end a splice direction.
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 the code of its cause (below), else ZMUX_CANCELLED.
A ctx cancelled by context.WithCancelCause with a cause that is, or wraps, a *StreamError (CancelCause(code) makes one) ends both streams in both directions with its ErrorCode: the downstream sending sides are reset and the upstream receiving sides stopped with it, and each direction's End is SpliceCancelled with Code set (an explicit 0 included). Any other cause, a plain cancel and a deadline reset the downstream sending sides with ZMUX_CANCELLED (StreamCancelled) and stop the upstream receiving sides with 0, and Code is ZMUX_CANCELLED.
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 DatagramsAsCapsules). 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. A ctx cancelled with a cause made by CancelCause ends both streams in both directions with that code, as in Splice; a plain cancel or a deadline resets with ZMUX_CANCELLED and stops with 0.
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
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
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
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
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. Flush succeeds once the data was sent: a STOP_SENDING or reset that the peer sent afterwards (a peer that refuses at once) is reported by the next Write, Read or Flush, not by this one; a stop or reset that came before the data was sent fails it. 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
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) NotifyReadable ¶ added in v1.5.2
NotifyReadable arranges for f to be called once a TryRead would return anything but ErrWouldBlock: data arrives, the part ends (FIN, reset, CancelRead, the session's end) or the read deadline passes. It returns stop, which cancels the call as the stop of context.AfterFunc does: true if it kept f from being called, false if f was called or started, or the call was stopped already; it does not wait for f, and calling it again is harmless.
f is called at most once, and exactly once unless stop cancels it. When the stream is readable already, f is called on the calling goroutine before NotifyReadable returns. Otherwise it runs on the goroutine of the event, such as the one that reads the connection or the deadline's timer, without any lock of the session held: f must not block, and may call the stream's methods, NotifyReadable included. Moving the read deadline while a call is pending calls f when the new deadline passes. The stream's datagrams and Close (which finishes only the sending part) do not make it readable. One call may be pending at a time: NotifyReadable panics while another is. No goroutine waits for a pending call.
func (*Stream) PathDatagramPayload ¶ added in v1.5.7
PathDatagramPayload returns the largest stream datagram payload, with context identifier contextID, that leaves as one datagram of the carrier instead of in a record (ConnectionState.PathDatagramPayload); 0 when the peer accepts none on this stream.
func (*Stream) PeerPriority ¶ added in v1.5.0
PeerPriority returns the priority this endpoint requested for the peer's sending part of the stream (the preamble's PRIORITY TLV or the last PRIORITY_UPDATE); ok is false when none was requested. It does not fail or wait.
func (*Stream) PipeCarrier ¶ added in v1.3.0
PipeCarrier reports whether the peer opened the stream as a pipe carrier.
func (*Stream) Preamble ¶ added in v1.3.0
Preamble returns the OPEN_INFO the peer opened the stream with.
func (*Stream) PreamblePriority ¶ added in v1.4.2
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
PreambleTLVs returns the application TLVs of the peer's preamble.
func (*Stream) Priority ¶ added in v1.5.0
Priority returns the local scheduling priority of the stream's sending part now: the last value SetPriority set or, where the peer's PRIORITY signals adjust it, the peer set. It does not fail or wait, and answers on a closed stream with the value it held last.
func (*Stream) Read ¶ added in v1.3.0
Read reads stream data; io.EOF only after a FIN that was not reset.
func (*Stream) ReadChunk ¶ added in v1.3.0
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
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
ReceiveDatagram returns the next stream datagram and its context identifier.
func (*Stream) ReceiveWindow ¶ added in v1.5.0
ReceiveWindow returns the stream's receive window settings: the initial window as set (or copied from the session), never the window auto-tuning has grown it to (that is the statistic RecvWindow), and the cap on it as set (0: automatic). It does not fail or wait.
func (*Stream) Redundant ¶ added in v1.5.0
Redundant returns what SetRedundant set: on, and whether it is set; unset, the stream follows the session. It does not fail or wait.
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
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) Scheduler ¶ added in v1.5.0
Scheduler returns the stream's own scheduling policy, nil while it follows the session's (never the session's policy it resolves to). It does not fail or wait, and answers on a closed stream with the value it held last.
func (*Stream) SendBuffer ¶ added in v1.5.0
SendBuffer returns the bound of the stream's written-but-unreleased bytes: the value SetSendBuffer set, else the one the session's configuration gave it. It does not fail or wait.
func (*Stream) SendCapacity ¶ added in v1.3.0
SendCapacity returns the bytes the sending part could transmit now.
func (*Stream) SendDatagram ¶ added in v1.3.0
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
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
SetDeadline sets both deadlines.
func (*Stream) SetPeerPriority ¶ added in v1.3.0
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
SetPipeCarrier marks the stream as a carrier of another session's pipe before the first frame.
func (*Stream) SetPreamble ¶ added in v1.3.0
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
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
SetReadDeadline sets the read deadline.
func (*Stream) SetReceiveWindow ¶ added in v1.3.0
SetReceiveWindow sets the stream's initial and maximum receive window. initial is advertised at once when it is above the window in force; credit already advertised is never withdrawn, so a lower initial only changes what ReceiveWindow reads back. limit caps auto-tuning, 0 making the cap automatic (whatever the session's configuration says). An initial below 4 KiB or a nonzero limit below initial is ErrInvalidConfig and changes nothing.
func (*Stream) SetRedundant ¶ added in v1.3.0
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
SetScheduler sets the stream's own scheduling policy; nil, the zero Scheduler, makes the stream follow the session's again.
func (*Stream) SetSendBuffer ¶ added in v1.3.0
SetSendBuffer bounds the stream's written-but-unreleased bytes.
func (*Stream) SetWriteDeadline ¶ added in v1.3.0
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 ¶
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) TryRead ¶ added in v1.5.0
TryRead reads what is readable now, up to len(p) bytes, and never waits. It returns what a Read would return at once: n > 0 bytes, io.EOF once the part ended with a FIN and everything was read, the read's error for a reset, a stop by this endpoint or the session's end, and os.ErrDeadlineExceeded once the read deadline passed with nothing readable. When nothing is readable yet it returns (0, ErrWouldBlock), as it does while another read of the stream is in progress (a blocked Read holds the read turn). An empty p returns (0, nil) unless the part ended. It does not allocate. With WaitReadable or NotifyReadable it is a Read that consumes nothing while it waits.
func (*Stream) TryWrite ¶ added in v1.4.10
TryWrite writes the prefix of p that fits in the send buffer now and returns its length, never waiting: 0 when nothing fits or another write is in progress (a WaitWritable included: pair the two in one goroutine). With WaitWritable it is a write that consumes nothing while it waits.
func (*Stream) TryWriteAll ¶ added in v1.3.0
TryWriteAll writes all of p now, or nothing when the send buffer has no room for it.
func (*Stream) WaitReadable ¶ added in v1.5.0
WaitReadable waits until a Read would not block: data is readable, or the receiving part ended (FIN, reset, CancelRead or the session's end), so that the next Read returns the data or that end, once, in its own form. It consumes nothing and returns nil in each of these cases; it fails only with its own bound: ctx's error when ctx ends first, and os.ErrDeadlineExceeded when the read deadline passes. Any number of goroutines may wait at once. A nil s returns net.ErrClosed.
func (*Stream) WaitSendCapacity ¶ added in v1.3.0
WaitSendCapacity waits until SendCapacity is at least n (or above 0 while nothing is unsent) and returns it. It waits for credit, not for what a write takes: see WaitWritable. It waits in turn with the stream's writes: a write blocked for room delays it, and it delays the next write.
func (*Stream) WaitWritable ¶ added in v1.4.10
WaitWritable waits until the send buffer has room for a write and returns the bytes TryWrite takes now (above 0), or the error that ended the sending part. Room, not credit, admits a write: it may be there while SendCapacity is 0, and the other way round. It consumes nothing, so ctx may cancel it at any point; the write deadline bounds it too. A write in progress on the stream finishes first. Then TryWrite takes at least the returned bytes unless other streams took the shared buffer meanwhile (0: wait again).
A WaitWritable in progress holds the stream's write turn, as a blocked Write does: a TryWrite from another goroutine returns 0 meanwhile. Call the two in one goroutine, WaitWritable then TryWrite.
func (*Stream) WriteChunk ¶ added in v1.3.0
WriteChunk writes a chunk without copying and takes ownership of it.
type StreamError ¶ added in v1.3.0
type StreamError struct {
StreamID StreamID
ErrorCode StreamErrorCode
// ReliableSize is the RESET_STREAM_AT Reliable Size of a reset.
ReliableSize uint64
Kind StreamErrorKind
Remote bool
}
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)
srv := make(chan *zmux.Conn, 1)
go func() {
s, err := zmux.Server(ctx, b, scfg)
srv <- s
ch <- err
}()
client, err = zmux.Client(ctx, a, ccfg)
server = <-srv
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 StreamErrorKind ¶ added in v1.5.7
type StreamErrorKind uint8
StreamErrorKind identifies the peer frame that ended a stream direction.
const ( // StreamErrorReset is a RESET_STREAM or RESET_STREAM_AT on reads. StreamErrorReset StreamErrorKind = iota + 1 // StreamErrorStopped is a STOP_SENDING on writes. StreamErrorStopped )
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.
The settings of a Switch other than the default.
type TCPPacketCounters ¶ added in v1.5.7
type TCPPacketCounters struct {
PacketsSent, PacketsRetransmitted uint64
}
TCPPacketCounters report Darwin outbound packets including retransmissions.
type TCPSegmentCounters ¶ added in v1.5.7
type TCPSegmentCounters struct {
DataSegsOut, TotalRetrans uint64
}
TCPSegmentCounters report Linux data segments and retransmitted segments.
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 Takeover ¶ added in v1.5.5
type Takeover struct {
// Info is the carrier's metadata, as Decide saw it.
Info CarrierInfo
// Value is Decision.Value of the verdict that handed the carrier over (nil after FallbackOnPeekTimeout): the host's routing
// of the carrier, as an accepted carrier's Value is its session's.
Value any
// contains filtered or unexported fields
}
Takeover is a carrier that the admission hands to the host (ListenerConfig.Fallback) on VerdictTakeover, on a stream or message carrier’s VerdictFallback, or on a prefix that Admission.FallbackOnPeekTimeout gave up on. What was read of it is replayed: the bytes of a byte stream, the first message of a message-framed carrier (always a whole, non-empty binary message: a carrier whose first read fails or returns an empty message is closed without a decision).
The carrier is the host's for the call of Fallback, whose context ends with the call at every entry point, and zmux closes it when Fallback returns, unless the host called Detach during the call: the carrier, and what an adapter runs it on (the QUIC connection of a stream, zmuxquic.TakeoverConn; the WebTransport session; the HTTP request of a request carrier), is then the host's for good, to be served after Fallback returned, on any goroutine and with a context of the host's, and closed by the host, which must close it once done.
Conn and Pipe are views of the one carrier, valid for as long as it is open: the host closes it through either (Conn's Close, or ClosePipeIO on Pipe). The views forward the capabilities of the carrier's halves (ConnectionStater, CarrierSecure, CloseWriter, Aborter, ...; see carrierview.go for the complete set and what a view reports for a capability its half lacks), and Unwrap returns the half under a view.
func (*Takeover) Conn ¶ added in v1.5.5
Conn returns the carrier as a net.Conn when it is a byte stream on a single net.Conn (TCP, TLS), sharing Pipe's replay: once the replayed bytes are read, WriteTo and ReadFrom use the connection's own (splice and sendfile where it offers them). It is a view of the connection that forwards its capabilities (ConnectionState, NetConn, CarrierSecure, CloseWrite, Abort, HandshakeContext, ...), its Close closing the connection once, and Unwrap returns the connection (read through it only once the replayed bytes were read).
func (*Takeover) Detach ¶ added in v1.5.5
Detach makes the carrier the host's: zmux does not close it when Fallback returns, and never touches it again; the host must close it once done (an HTTP request carrier's handler waits for that, bounded only by the request's context). It is called during Fallback, which may then hand Conn or Pipe to another goroutine and return; the context Fallback got ends with the call, so the host serves the carrier on with a context of its own. A second Detach returns nil. After Fallback returned without Detach it returns ErrTakeoverReturned (the carrier is closed), and net.ErrClosed when the host closed every half of the carrier before.
func (*Takeover) Messages ¶ added in v1.5.5
func (t *Takeover) Messages() (MessageReader, MessageWriter, bool)
Messages returns the halves of a message-framed carrier (Framing FramingRecords, such as WebSocket), the reader returning the first message again first; false for a byte stream. A half the carrier does not have is nil.
func (*Takeover) Pipe ¶ added in v1.5.5
Pipe returns the carrier with what was read replayed: its receiving half is a view that returns what was read first (on a message-framed carrier, Framing FramingRecords, a MessageReader that returns the first message again first); its sending half is the carrier's own, except where Conn applies, whose view both halves then are. Each half is a view that closes the carrier's half once, whoever closes it (the host, or zmux when Fallback returns without Detach): ClosePipeIO closes the carrier, and a half can be closed on its own (close the sending half, read the receiving one to its end).
type Tracer ¶ added in v1.3.0
type Tracer struct {
// Established: the peer's transport parameters were processed. It is
// the first call.
Established func(id SessionID)
// Event: each occurrence of a pipe or session event, before NextEvent's
// queue merges it: a JoinAuthFailed has Count 1, and every retired pipe
// is one EventPipesRetired.
Event func(id SessionID, ev Event)
// StreamEvents enables per-frame placement and receive-gap events in Event
// for multipath sessions. These events share the Tracer's drop accounting.
StreamEvents bool
// Dropped: this many of the session's events were lost since the
// previous call because its backlog was full. It is called where the
// lost events stood: before the next event the backlog accepted, or
// before Closed, never after it.
Dropped func(id SessionID, count uint64)
// Closed: the session ended. It is the last call: nothing follows it,
// and what occurs after the session ended is not traced.
Closed func(id SessionID, 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: each session has a backlog of 256 events, fixed and not configurable, and an event that finds it full is dropped and counted (the Tracer observes; an application that must not lose events reads NextEvent, whose queue never drops). Established, Dropped and Closed take no room of the backlog and are never dropped. Wait and Done do not wait for the Tracer (nor for Pick or AllowConnectionWindowIncrease), so a hook may call Wait or Done; Closed may run after Wait returned.
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 {
// 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
// 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
// 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
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
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.
type VariantStat ¶ added in v1.3.3
type VariantStat struct {
// Name is the label, empty for the Overflow bucket.
Name string
// Overflow marks the bucket of the variants past MaxAdmissionVariants.
Overflow bool
Accepted, Fallback uint64
// Takeover counts carriers delivered to the byte-stream target on VerdictTakeover.
Takeover uint64
// Stalled counts stall outcomes, including Takeover without a target
// and stalls that exceed the quota.
Stalled uint64
// Closed counts Close outcomes labeled with this variant.
Closed uint64
}
VariantStat are the admission outcomes of one Decision.Variant (Listener.VariantStats).
type WrapPipeFunc ¶ added in v1.4.0
WrapPipeFunc is a function used as a PipeWrapper.
Source Files
¶
- admission.go
- alpn.go
- attachment.go
- backoff.go
- bufpool.go
- carrier_linux.go
- carrier_sample.go
- carrier_tcp.go
- carrierview.go
- channel.go
- clock.go
- clock_other.go
- config.go
- conn.go
- credential.go
- deadline.go
- doc.go
- driver.go
- duplicate.go
- early.go
- epoch.go
- errors.go
- events.go
- handlers.go
- hooks.go
- joinio.go
- joinoutcome.go
- labels.go
- lanes.go
- listener.go
- listener_adapter.go
- listener_limits.go
- listener_registry.go
- liveness.go
- maintain.go
- mode.go
- nested.go
- packet.go
- packetsplice.go
- pipeconn.go
- pipeio.go
- pipes.go
- poolpolicy.go
- quality.go
- refused.go
- scheduler.go
- securetls.go
- shaping.go
- splice.go
- stream.go
- stream_ops.go
- trusted.go
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. |
|
carrierstats
Package carrierstats shares lazy native observations across a connection's users.
|
Package carrierstats shares lazy native observations across a connection's users. |
|
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. |
|
poolhost
Package poolhost holds what the pools of the root package and of carrier share: the order in which a shrinking pool closes members and how a rejected policy decision is reported.
|
Package poolhost holds what the pools of the root package and of carrier share: the order in which a shrinking pool closes members and how a rejected policy decision is reported. |
|
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. |
|
testscale
Package testscale scales the time budgets of tests that wait for something to happen, so that they hold on a loaded host and under the race detector: a budget is an upper bound, which a passing test never waits for whole, so scaling it costs a passing run nothing.
|
Package testscale scales the time budgets of tests that wait for something to happen, so that they hold on a loaded host and under the race detector: a budget is an upper bound, which a passing test never waits for whole, so scaling it costs a passing run nothing. |
|
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
|