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 Listener.ServeHTTP accept any carrier. The sub-modules zmuxquic and zmuxh3 carry sessions over QUIC, HTTP/3 and WebTransport.
The Conn and Stream methods follow quic-go: OpenStream[Sync], AcceptStream, Read, Write, Close (FIN), CancelRead, CancelWrite, deadlines, SendDatagram and ReceiveDatagram. StreamConn gives a stream the net.Conn interface.
Blocking: calls that wait take a context.Context (OpenStreamSync, AcceptStream, Ping, Shutdown, AddPipe, NextEvent, ...) or honour the stream's deadlines (Read, Write). Close, CloseWithError, CancelRead, CancelWrite and Pipe.Close never block; Wait blocks until the session and all its goroutines ended. Conn.Context and Stream.Context are the session's context.
Closing: Conn.Close ends the session at once and discards data not yet sent; Conn.Shutdown lets open streams finish first. Listener.Shutdown does the same for every session of a listener.
Ownership: a Stream handle that is garbage-collected without being closed resets and stops its stream, so keep it while it is in use. A net.Conn given to Client or Server and a PipeIO given to Start, AddPipe or HandlePipe belong to zmux from then on, which closes each half exactly once, unless the call fails with ErrInvalidConfig before taking it. A Chunk from ReadChunk is released exactly once, by Release or by WriteChunk.
Events ¶
Pipe changes and other session events (EventKind) can be read with Conn.NextEvent, or received with a Config.Tracer; both are optional and bounded, and the current state is always available from Conn.PipeStats and Conn.ConnectionState.
Errors ¶
A session's end is one of *ApplicationError, *TransportError, *IdleTimeoutError, *HandshakeTimeoutError, *EarlyDataRejectedError, *ResumeTimeoutError or *PipesLostError. Every one matches net.ErrClosed with errors.Is; the last five also match their sentinel (ErrIdleTimeout, ErrHandshakeTimeout, ErrEarlyDataRejected, ErrResumeTimeout, ErrPipesLost), the timeouts also os.ErrDeadlineExceeded, and the two that a lost pipe caused unwrap to that pipe's error. A stream the peer reset or stopped gives a *StreamError. IsRetryable reports streams the peer did not process (ErrRejected, ErrGoingAway, ErrEarlyDataRejected), which can be sent again. Calls fail with ErrStreamClosed, ErrNotNegotiated, ErrNotEstablished, ErrTooLate, ErrInvalidConfig, ErrPipeGone or ErrNoDecision where their documentation says so.
Names ¶
Constants carry the name of their type as a prefix: Role (RoleClient), Dir (DirSendOnly), Framing (FramingRecords), Urgency (UrgencyDefault), Event (EventPipeJoined), Transport for transport error codes (TransportProtocolViolation) and Stream for stream error codes (StreamCancelled).
Configuration ¶
The zero value of every Config field selects its default. For sizes, counts and durations that can be turned off or unlimited, a negative value means off or unlimited (MaxIdleTimeout, MemoryBudget, MaxIncomingStreams, ListenerConfig.MemoryBudget); pointer fields distinguish "unset" where zero is itself meaningful. Multipath needs MaxPipes above 1 and a PipeAuth (PSK or TLS); without a secret, joins are possible only with PipeAuth.AllowInsecure, meant for tests and protected networks.
Example (Tcp) ¶
Example_tcp serves zmux on a TCP listener and dials it. The Listener is the server for every kind of client, including those that later join more pipes to their session.
package main
import (
"context"
"fmt"
"io"
"net"
"time"
"github.com/zmuxio/zmux-go"
)
// echo answers every stream of conn with what it read, until conn ends.
func echo(ctx context.Context, conn *zmux.Conn) {
for {
st, err := conn.AcceptStream(ctx)
if err != nil {
return
}
go func() {
_, _ = io.Copy(st, st)
_ = st.Close()
}()
}
}
// roundTrip opens a stream, sends msg, finishes the stream and returns the
// answer.
func roundTrip(ctx context.Context, conn *zmux.Conn, msg string) (string, error) {
st, err := conn.OpenStreamSync(ctx)
if err != nil {
return "", err
}
if _, err := st.Write([]byte(msg)); err != nil {
return "", err
}
if err := st.Close(); err != nil {
return "", err
}
b, err := io.ReadAll(st)
return string(b), err
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// Server.
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
fmt.Println(err)
return
}
l := zmux.NewListener(nil)
go func() { _ = l.Serve(ctx, ln) }()
go func() {
for {
conn, err := l.Accept(ctx)
if err != nil {
return
}
go echo(ctx, conn)
}
}()
// Client.
conn, err := zmux.Dial(ctx, "tcp", ln.Addr().String(), nil)
if err != nil {
fmt.Println(err)
return
}
reply, err := roundTrip(ctx, conn, "hello over TCP")
if err != nil {
fmt.Println(err)
return
}
fmt.Println(reply)
// Graceful end: the client, then every session of the listener.
_ = conn.Shutdown(ctx, 0, "")
_ = l.Shutdown(ctx, 0, "")
}
Output: hello over TCP
Example (WebSocket) ¶
Example_webSocket runs a session over a message-framed carrier such as WebSocket, through the adapter wsPipe above; an in-memory connection stands in for the WebSocket library here.
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
ca, sa := memWebSocketPair()
done := make(chan *zmux.Conn, 1)
go func() {
server, err := zmux.Start(ctx, wsPipe(sa), zmux.RoleServer, nil)
if err != nil {
done <- nil
return
}
go echo(ctx, server)
done <- server
}()
client, err := zmux.Start(ctx, wsPipe(ca), zmux.RoleClient, nil)
if err != nil {
fmt.Println(err)
return
}
server := <-done
if server == nil {
_ = client.Close()
fmt.Println("server failed")
return
}
defer closeBoth(client, server)
reply, err := roundTrip(ctx, client, "hello over messages")
if err != nil {
fmt.Println(err)
return
}
fmt.Println(reply)
Output: hello over messages
Index ¶
- Constants
- Variables
- func HandleLane(ctx context.Context, p PipeIO) error
- func IsRetryable(err error) bool
- func StreamConn(s *Stream, local, remote net.Addr) net.Conn
- type ApplicationError
- type ApplicationErrorCode
- type CapacityFloor
- type CarrierPool
- type Chunk
- 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 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) AcceptStream(ctx context.Context) (*Stream, error)
- func (c *Conn) AcceptUniStream(ctx context.Context) (*ReceiveStream, error)
- func (c *Conn) AddPipe(ctx context.Context, p PipeIO, o PipeOptions) (*Pipe, error)
- func (c *Conn) Close() error
- func (c *Conn) CloseWithError(code ApplicationErrorCode, msg string) error
- func (c *Conn) ConnectionState() ConnectionState
- func (c *Conn) ConnectionStats() ConnectionStats
- func (c *Conn) Context() context.Context
- func (c *Conn) DesignateDialer(local bool)
- func (c *Conn) JoinReady() bool
- 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, tlvs ...TLV) (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 uint64) (*Pipe, bool)
- func (c *Conn) PipeStats() []PipeStats
- func (c *Conn) Pipes() []*Pipe
- func (c *Conn) ReceiveDatagram(ctx context.Context) ([]byte, error)
- func (c *Conn) RememberedParameters() []byte
- func (c *Conn) RemoteAddr() net.Addr
- func (c *Conn) ReservePipe(dir Direction, o PipeOptions) (*Reservation, error)
- func (c *Conn) RevalidatePipes() error
- func (c *Conn) SendDatagram(p []byte) error
- func (c *Conn) SendDatagramWait(ctx context.Context, p []byte) error
- func (c *Conn) SetCapacityFloor(f CapacityFloor)
- func (c *Conn) SetQualityBand(b QualityBand)
- func (c *Conn) SetScheduler(s Scheduler)
- func (c *Conn) Shutdown(ctx context.Context, code ApplicationErrorCode, msg string) error
- func (c *Conn) Wait() error
- type ConnectionState
- type ConnectionStats
- type DatagramLimiter
- type DatagramTooLargeError
- type Direction
- type DuplicateOptions
- type DuplicateResult
- type EarlyClientCarrier
- type EarlyData
- type EarlyDataRejectedError
- type EarlyServerCarrier
- type Event
- type EventKind
- type Framing
- type GoAway
- type HandshakeTimeoutError
- type IdleTimeoutError
- type JoinHint
- type Lease
- type Limiter
- type Listener
- func (l *Listener) Accept(ctx context.Context) (*Conn, error)
- func (l *Listener) Close() error
- func (l *Listener) HandlePipe(ctx context.Context, p PipeIO, hint JoinHint) error
- func (l *Listener) MemoryUsed() uint64
- func (l *Listener) Serve(ctx context.Context, ln net.Listener) error
- func (l *Listener) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (l *Listener) Shutdown(ctx context.Context, code ApplicationErrorCode, msg string) error
- type ListenerConfig
- type MessageReader
- type MessageWriter
- type PeerRequest
- type Pick
- type PickAnswer
- type PickPipe
- type PickRequest
- type Pipe
- func (p *Pipe) Abort(cause error) error
- func (p *Pipe) ClearSendPriority() error
- func (p *Pipe) ClearSendStandby() error
- func (p *Pipe) Close() error
- func (p *Pipe) ID() uint64
- func (p *Pipe) Revalidate() error
- func (p *Pipe) SetProbation(d time.Duration) error
- func (p *Pipe) SetQualityBand(b QualityBand) error
- func (p *Pipe) SetReceivePriority(v uint64) error
- func (p *Pipe) SetReceiveStandby(b bool) error
- func (p *Pipe) SetSendPriority(v uint64) error
- func (p *Pipe) SetSendStandby(b bool) error
- func (p *Pipe) SetWeight(w uint64) error
- func (p *Pipe) Stats() (PipeStats, error)
- type PipeAuth
- type PipeIO
- type PipeOptions
- type PipePool
- type PipeStats
- type PipesLostError
- type PoolLimits
- type QualityBand
- type ReceiveStream
- func (s *ReceiveStream) CancelRead(code StreamErrorCode)
- func (s *ReceiveStream) Preamble() []byte
- func (s *ReceiveStream) PreambleTLVs() []TLV
- func (s *ReceiveStream) Read(p []byte) (int, error)
- func (s *ReceiveStream) ReadChunk(ctx context.Context, max int) (Chunk, error)
- 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, max uint64)
- func (s *ReceiveStream) StreamID() StreamID
- func (s *ReceiveStream) WriteTo(w io.Writer) (int64, error)
- type Reservation
- 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) Close() error
- func (s *SendStream) ReadFrom(r io.Reader) (int64, error)
- 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) StreamID() StreamID
- func (s *SendStream) TryWriteAll(p []byte) (bool, error)
- func (s *SendStream) WaitSendCapacity(ctx context.Context, min uint64) (uint64, error)
- func (s *SendStream) Write(p []byte) (int, error)
- func (s *SendStream) WriteChunk(ctx context.Context, c Chunk) error
- type SpliceDirection
- 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) Close() error
- func (s *Stream) Context() context.Context
- func (s *Stream) PipeCarrier() bool
- func (s *Stream) Preamble() []byte
- func (s *Stream) PreambleTLVs() []TLV
- func (s *Stream) Read(p []byte) (int, error)
- func (s *Stream) ReadChunk(ctx context.Context, max 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) Reject()
- func (s *Stream) Replayable() bool
- 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, max uint64)
- 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) StreamID() StreamID
- func (s *Stream) TryWriteAll(p []byte) (bool, error)
- func (s *Stream) WaitSendCapacity(ctx context.Context, min uint64) (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 StreamID
- type StreamLimitReachedError
- type TLV
- type Tracer
- type TransportError
- type TransportErrorCode
- type Urgency
Examples ¶
Constants ¶
const ( HeaderJoin = "Zmux-Pipe-Join" HeaderPair = "Zmux-Pipe-Pair" )
HTTP carriers: a request body carries the up direction, a response body the down direction. HTTP/2 and HTTP/3 requests (and HTTP/1.1 with full duplex) carry both; a split bootstrap pairs an uplink POST and a downlink GET by the Zmux-Pipe-Pair header (SPEC.md 6.1.1), and a pipe that cannot write first joins out of band with Zmux-Pipe-Join (MULTIPATH.md 5.3).
const MaxInstanceIDLen = 8
MaxInstanceIDLen bounds ListenerConfig.InstanceID so that at least 8 random bytes remain in the 16-byte session locator.
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") // 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. ErrStreamClosed = errors.New("zmux: stream closed") // ErrNotNegotiated is returned for features the session does not use. ErrNotNegotiated = errors.New("zmux: feature not negotiated") // ErrNotEstablished is returned for calls that need the peer's // parameters before they arrived. ErrNotEstablished = errors.New("zmux: session not established") // ErrRejected reports a stream the peer did not process (ZMUX_REJECTED // or at or above a GOAWAY watermark); it is retryable. ErrRejected = errors.New("zmux: stream rejected") // ErrGoingAway reports an open after 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") // ErrPipeGone is returned by Pipe methods once the session no longer // knows the attachment. ErrPipeGone = errors.New("zmux: pipe gone") // ErrNoDecision is returned by ResolveDuplicate when no input of the // duplicate-session rule decides between the two sessions. ErrNoDecision = errors.New("zmux: the duplicate-session rule has no input that decides") )
Errors of individual calls.
Functions ¶
func 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. It blocks until the lane ends.
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 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)
go func() {
var err error
server, err = zmux.Server(ctx, b, scfg)
ch <- err
}()
client, err = zmux.Client(ctx, a, ccfg)
if serr := <-ch; err == nil {
err = serr
}
if err != nil {
if client != nil {
_ = client.Close()
}
if server != nil {
_ = server.Close()
}
return nil, nil, err
}
return client, server, nil
}
// closeBoth closes both sessions and waits for their ends.
func closeBoth(a, b *zmux.Conn) {
_ = a.Close()
_ = b.Close()
_ = a.Wait()
_ = b.Wait()
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
client, server, err := sessions(ctx, nil, nil)
if err != nil {
fmt.Println(err)
return
}
defer closeBoth(client, server)
go func() {
st, err := server.AcceptStream(ctx)
if err != nil {
return
}
_, _ = io.Copy(st, st) // echo
_ = st.Close()
}()
st, err := client.OpenStreamSync(ctx)
if err != nil {
fmt.Println(err)
return
}
nc := zmux.StreamConn(st, client.LocalAddr(), client.RemoteAddr())
if _, err := nc.Write([]byte("hello")); err != nil {
fmt.Println(err)
return
}
buf := make([]byte, 5)
if _, err := io.ReadFull(nc, buf); err != nil {
fmt.Println(err)
return
}
fmt.Println(string(buf))
// Close finishes the stream and stops reading, as net.Conn users expect.
_ = nc.Close()
}
Output: hello
Types ¶
type ApplicationError ¶
type ApplicationError struct {
Remote bool
ErrorCode ApplicationErrorCode
ErrorMessage string
}
ApplicationError is a session closed by an application (CONNECTION_CLOSE 0x1d).
func (*ApplicationError) Error ¶
func (e *ApplicationError) Error() string
Error describes the close.
func (*ApplicationError) Is ¶
func (e *ApplicationError) Is(t error) bool
Is makes every session termination match net.ErrClosed.
type ApplicationErrorCode ¶ added in v1.3.0
type ApplicationErrorCode uint64
ApplicationErrorCode is an application error code (62 bits).
type 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/s), and EventCapacityRestored once it is back at Rate*RateRatio. A zero Rate turns it off, so the zero CapacityFloor reports nothing; a zero RateRatio means 1.25.
type CarrierPool ¶ added in v1.3.0
type CarrierPool[C comparable] struct { // Dial opens an underlying connection. Dial func(ctx context.Context) (C, error) // Close closes a connection the pool retired once no pipe uses it. Close func(C) // PoolLimits bound the use of each connection; set them before the // first Get. PoolLimits // contains filtered or unexported fields }
CarrierPool shares underlying connections between pipes, for adapters that carry several pipes over one connection (HTTP/2 and HTTP/3 request streams, QUIC streams). A new pipe goes to the open connection with the most room within the limits, else to a new one; a connection that reached its lifetime limits takes no new pipe and is closed once its last pipe ends. The pipes of one connection get one fate group: they fail together and are never counted as independent paths. The zero value with Dial set is ready; it is safe for concurrent use.
func (*CarrierPool[C]) Get ¶ added in v1.3.0
func (p *CarrierPool[C]) Get(ctx context.Context) (*Lease[C], error)
Get returns a lease on a connection with room, dialling one when none has; the dial runs outside the pool's lock.
func (*CarrierPool[C]) RetireConn ¶ added in v1.3.0
func (p *CarrierPool[C]) RetireConn(c C)
RetireConn retires connection c (for example when it failed): it takes no new pipe and closes once its pipes are released.
func (*CarrierPool[C]) Shutdown ¶ added in v1.3.0
func (p *CarrierPool[C]) Shutdown()
Shutdown retires every connection: idle ones close now, the others when their last pipe ends; Get fails afterwards.
type 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.
type Config ¶
type Config struct {
// HandshakeTimeout bounds establishment and join confirmation (10 s).
HandshakeTimeout time.Duration
// MaxIdleTimeout is max_idle_timeout (30 s); negative disables it.
MaxIdleTimeout time.Duration
// KeepAlivePeriod sends a QX_PING when the session is idle this long
// (0: off). It must be below the effective idle timeout.
KeepAlivePeriod time.Duration
// InitialStreamReceiveWindow (256 KiB, at least 4 KiB).
InitialStreamReceiveWindow uint64
// MaxStreamReceiveWindow caps auto-tuning (0: auto, a 64 MiB floor
// that grows within the memory budget).
MaxStreamReceiveWindow uint64
// LatencyBudget is the B of window auto-tuning (100 us).
LatencyBudget time.Duration
// InitialConnectionReceiveWindow (1 MiB, at least 16 KiB).
InitialConnectionReceiveWindow uint64
// MaxConnectionReceiveWindow (0: auto, a 96 MiB floor).
MaxConnectionReceiveWindow uint64
// MemoryBudget of a session without a listener (1 GiB); negative is
// unlimited.
MemoryBudget int64
// MaxIncomingStreams is initial_max_streams_bidi (256); negative is 0.
MaxIncomingStreams int64
// MaxIncomingUniStreams: 0 = staged credit (16, raised to 256 on the
// first AcceptUniStream); negative = explicit 0; positive = that value.
MaxIncomingUniStreams int64
// EnableDatagrams announces max_datagram_frame_size and datagram flows.
EnableDatagrams bool
// Datagram queue sizes (64 / 128 / 32 per stream / 1 MiB).
DatagramSendQueue int
DatagramReceiveQueue int
DatagramStreamQueue int
DatagramReceiveBytes int
// SendBuffer bounds written-but-unreleased bytes (4 MiB).
SendBuffer uint64
// MaxSendBuffer bounds its growth in multipath sessions (0: auto).
MaxSendBuffer uint64
// MaxPipes is the attachments this endpoint aims for (1: multipath
// off; 8 recommended when multipath is used).
MaxPipes int
// PipeHeadroom is H of the attachment cap (8).
PipeHeadroom int
// ReplayWindow is W (default max(64, 2*(MaxPipes+H))).
ReplayWindow int
// MaxLanes is the lanes accepted per inbound pipe (258; 1 disables).
MaxLanes int
// ResumeTimeout enables resume with this grace period.
ResumeTimeout time.Duration
// Scheduler is the session's scheduling policy (nil: Affinity).
Scheduler Scheduler
// SchedulerParams tune the scheduler and failure detection.
SchedulerParams SchedulerParams
// PipeAuth selects the join secret (required for multipath).
PipeAuth PipeAuth
// EarlyData enables early data (SPEC.md 6.1.2).
EarlyData EarlyData
// DatagramLimiter polices datagrams in each direction:
// a datagram passes when TryReady allows its whole payload, and is
// then charged; otherwise it is dropped and counted.
DatagramLimiter DatagramLimiter
// Tracer receives session events on a goroutine of its own.
Tracer *Tracer
// Redial re-establishes pipes after failures (resume).
Redial func(ctx context.Context, need Direction) (PipeIO, error)
// AllowConnectionWindowIncrease approves session window growth.
AllowConnectionWindowIncrease func(delta uint64) bool
}
Config configures a session. The zero value of every field selects its default; nil *Config means all defaults.
type Conn ¶
type Conn struct {
// contains filtered or unexported fields
}
Conn is a zmux session. Its methods are safe for concurrent use.
Concurrency model: one mutex guards the sans-IO core; no I/O, blocking or application code runs under it. Each pipe direction has a reader and a writer goroutine; wake-ups are queued under the lock and delivered after it is released.
func Client ¶
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. The session owns c from then on, unless Client fails with ErrInvalidConfig.
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 the session owns from then on. It returns as Start does; ctx bounds the dial and the handshake.
func DialTLS ¶ added in v1.3.0
func DialTLS(ctx context.Context, network, addr string, tlsConf *tls.Config, cfg *Config) (*Conn, error)
DialTLS connects to addr on the named network, runs the TLS handshake with tlsConf (as tls.Dialer.DialContext) and starts a client session on the TLS connection, which the session owns from then on. ctx bounds the dial and both handshakes.
Example ¶
ExampleDialTLS serves zmux over TLS (tls.NewListener) and dials it with DialTLS.
package main
import (
"context"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/tls"
"crypto/x509"
"fmt"
"io"
"math/big"
"net"
"time"
"github.com/zmuxio/zmux-go"
)
// echo answers every stream of conn with what it read, until conn ends.
func echo(ctx context.Context, conn *zmux.Conn) {
for {
st, err := conn.AcceptStream(ctx)
if err != nil {
return
}
go func() {
_, _ = io.Copy(st, st)
_ = st.Close()
}()
}
}
// roundTrip opens a stream, sends msg, finishes the stream and returns the
// answer.
func roundTrip(ctx context.Context, conn *zmux.Conn, msg string) (string, error) {
st, err := conn.OpenStreamSync(ctx)
if err != nil {
return "", err
}
if _, err := st.Write([]byte(msg)); err != nil {
return "", err
}
if err := st.Close(); err != nil {
return "", err
}
b, err := io.ReadAll(st)
return string(b), err
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
serverTLS, clientTLS, err := testTLSConfigs()
if err != nil {
fmt.Println(err)
return
}
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
fmt.Println(err)
return
}
l := zmux.NewListener(nil)
go func() { _ = l.Serve(ctx, tls.NewListener(ln, serverTLS)) }()
go func() {
for {
conn, err := l.Accept(ctx)
if err != nil {
return
}
go echo(ctx, conn)
}
}()
conn, err := zmux.DialTLS(ctx, "tcp", ln.Addr().String(), clientTLS, nil)
if err != nil {
fmt.Println(err)
return
}
reply, err := roundTrip(ctx, conn, "hello over TLS")
if err != nil {
fmt.Println(err)
return
}
fmt.Println(reply)
_ = conn.Shutdown(ctx, 0, "")
_ = l.Shutdown(ctx, 0, "")
}
// testTLSConfigs returns TLS configurations with a fresh self-signed
// certificate for 127.0.0.1.
func testTLSConfigs() (server, client *tls.Config, err error) {
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
return nil, nil, err
}
tmpl := &x509.Certificate{
SerialNumber: big.NewInt(1),
NotBefore: time.Now().Add(-time.Hour),
NotAfter: time.Now().Add(time.Hour),
IPAddresses: []net.IP{net.IPv4(127, 0, 0, 1)},
KeyUsage: x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
}
der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key)
if err != nil {
return nil, nil, err
}
cert, err := x509.ParseCertificate(der)
if err != nil {
return nil, nil, err
}
pool := x509.NewCertPool()
pool.AddCert(cert)
server = &tls.Config{Certificates: []tls.Certificate{{Certificate: [][]byte{der}, PrivateKey: key}},
MinVersion: tls.VersionTLS13}
client = &tls.Config{RootCAs: pool, MinVersion: tls.VersionTLS13}
return server, client, nil
}
Output: hello over TLS
func Server ¶
Server starts a single-pipe server session on an accepted connection, like tls.Server. For multipath, resume or pipe joins use a Listener (Listener.Serve accepts sessions and joins on a net.Listener): Server rejects Config.MaxPipes above 1 with ErrInvalidConfig. The session owns c from then on, unless Server fails with ErrInvalidConfig.
func Start ¶ added in v1.3.0
Start establishes a session over any carrier with an explicit role. It returns once the peer's transport parameters were processed, or at once when the session may send early data (EarlyData.ZmuxPeer, or EarlyData.Replayable with Remembered parameters); ConnectionState's Established is false until the parameters arrive.
func (*Conn) AcceptStream ¶
AcceptStream returns the next bidirectional stream the peer opened.
func (*Conn) AcceptUniStream ¶
func (c *Conn) AcceptUniStream(ctx context.Context) (*ReceiveStream, error)
AcceptUniStream returns the next unidirectional stream the peer opened. The first call grants the staged unidirectional credit.
func (*Conn) AddPipe ¶ added in v1.3.0
AddPipe joins a new carrier to the session in band (MULTIPATH.md 5.7) and waits until the join is confirmed, the pipe fails, or ctx ends (the pipe is then removed). A join that the attachment cap or the refusal backoff holds waits for room.
Example ¶
ExampleConn_AddPipe joins a second pipe to a session and follows its state with NextEvent. Multipath needs MaxPipes above 1 and a join secret on both sides, and a Listener on the server.
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
cfg := &zmux.Config{MaxPipes: 2, PipeAuth: zmux.PipeAuth{PSK: []byte("an example pre-shared key, 32 B")}}
l := zmux.NewListener(&zmux.ListenerConfig{Config: cfg})
defer func() { _ = l.Close() }()
// Two carriers between the same endpoints (two paths in practice).
a0, b0 := net.Pipe()
a1, b1 := net.Pipe()
go func() { _ = l.HandlePipe(ctx, zmux.NetPipe(b0), zmux.JoinHint{}) }()
go func() { _ = l.HandlePipe(ctx, zmux.NetPipe(b1), zmux.JoinHint{}) }()
client, err := zmux.Client(ctx, a0, cfg)
if err != nil {
fmt.Println(err)
return
}
server, err := l.Accept(ctx)
if err != nil {
fmt.Println(err)
return
}
defer closeBoth(client, server)
standby := true
p, err := client.AddPipe(ctx, zmux.NetPipe(a1), zmux.PipeOptions{Label: "backup", SendStandby: &standby})
if err != nil {
fmt.Println(err)
return
}
for {
ev, err := client.NextEvent(ctx)
if err != nil {
fmt.Println(err)
return
}
if ev.Kind == zmux.EventPipeJoined && ev.Pipe == p.ID() {
break
}
}
st, err := p.Stats()
if err != nil {
fmt.Println(err)
return
}
fmt.Println(len(client.Pipes()), "pipes;", st.Label, st.State, "standby:", st.Standby)
Output: 2 pipes; backup active standby: true
func (*Conn) Close ¶
Close closes the session at once with application error code 0, discarding data not yet sent; it never blocks. Unlike net.Conn.Close it does not flush: to let the peer read what was written, call Shutdown(ctx, 0, "") instead. Wait waits for the end.
func (*Conn) CloseWithError ¶ added in v1.0.4
func (c *Conn) CloseWithError(code ApplicationErrorCode, msg string) error
CloseWithError closes the session immediately with an application error; it never blocks. Unsent data is discarded.
func (*Conn) ConnectionState ¶ added in v1.3.0
func (c *Conn) ConnectionState() ConnectionState
ConnectionState returns the negotiation results.
func (*Conn) ConnectionStats ¶ added in v1.3.0
func (c *Conn) ConnectionStats() ConnectionStats
ConnectionStats returns a snapshot of the counters.
func (*Conn) Context ¶ added in v1.3.0
Context is canceled when the session ends; context.Cause returns its error.
func (*Conn) DesignateDialer ¶ added in v1.3.0
DesignateDialer records which endpoint dialed a session whose bootstrap carrier is symmetric (role auto), for ResolveDuplicate.
func (*Conn) JoinReady ¶ added in v1.3.0
JoinReady reports whether a pipe added now would join at once rather than wait for the attachment cap or the refusal backoff: dial a carrier only then, so that none is held idle.
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. It dials outside every lock and returns ctx's error or the session's.
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 queue of the session bounded at 1024 events. Reading it is optional: when nobody calls NextEvent the oldest events are dropped (ConnectionStats.EventsDropped counts them), so a reader that falls behind sees the latest events and can read the current state with PipeStats. The queue is independent of Config.Tracer: a Tracer receives every event as well, on its own bounded queue, whether or not NextEvent is called. Concurrent callers each receive different events.
func (*Conn) OpenPipeStream ¶ added in v1.3.0
OpenPipeStream opens a stream of c to carry a pipe pair of another session; tlvs are application TLVs of its preamble (for example routing metadata for relays), to which PIPE_CARRIER is added. Nothing is sent before the nested session writes its first record.
func (*Conn) OpenStream ¶
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, taken in one critical section. 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) ReceiveDatagram ¶ added in v1.3.0
ReceiveDatagram returns the next session datagram.
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) ReservePipe ¶ added in v1.3.0
func (c *Conn) ReservePipe(dir Direction, o PipeOptions) (*Reservation, error)
ReservePipe reserves a pipe for an out-of-band join.
func (*Conn) RevalidatePipes ¶ added in v1.3.0
RevalidatePipes revalidates every live outbound pipe (after a network change).
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) SetCapacityFloor ¶ added in v1.3.0
func (c *Conn) SetCapacityFloor(f CapacityFloor)
SetCapacityFloor sets the capacity floor of the outbound direction.
func (*Conn) SetQualityBand ¶ added in v1.3.0
func (c *Conn) SetQualityBand(b QualityBand)
SetQualityBand sets the default band of the session's pipes.
func (*Conn) SetScheduler ¶ added in v1.3.0
SetScheduler changes the session's scheduling policy; it applies from the next chunk.
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 CloseWithError(code, msg) and returns ctx's error. The usual call is
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() err := conn.Shutdown(ctx, 0, "")
Example ¶
ExampleConn_Shutdown ends a session gracefully: the stream the server is still reading is delivered in full before the session closes, which Close would not wait for.
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
client, server, err := sessions(ctx, nil, nil)
if err != nil {
fmt.Println(err)
return
}
defer closeBoth(client, server)
got := make(chan int, 1)
go func() {
st, err := server.AcceptStream(ctx)
if err != nil {
got <- -1
return
}
b, _ := io.ReadAll(st)
_ = st.Close()
got <- len(b)
}()
st, err := client.OpenStreamSync(ctx)
if err != nil {
fmt.Println(err)
return
}
if _, err := st.Write(make([]byte, 1<<20)); err != nil {
fmt.Println(err)
return
}
_ = st.Close()
go func() { _, _ = io.Copy(io.Discard, st) }()
if err := client.Shutdown(ctx, 0, "done"); err != nil {
fmt.Println(err)
return
}
fmt.Println("server read", <-got, "bytes")
Output: server read 1048576 bytes
type ConnectionState ¶ added in v1.3.0
type ConnectionState struct {
Role Role
Established bool
SupportsDatagrams struct{ Local, Remote bool }
SupportsResetAt struct{ Local, Remote bool }
Multipath bool
PipeAck bool
Resume bool
JoinSecurityAbsent bool
PeerIsZmux bool
PeerGoAway *GoAway
MaxDatagramPayload int
}
ConnectionState reports the negotiation results.
type ConnectionStats ¶ added in v1.3.0
type ConnectionStats struct {
BytesSent, BytesReceived uint64
RecordsSent, RecordsReceived uint64
StreamsOpenedLocal uint64
StreamsOpenedRemote uint64
DatagramsSent uint64
DatagramsReceived uint64
DatagramsDroppedSend uint64
DatagramsDroppedRecv uint64
DatagramsDroppedLimit uint64
BytesWritten, BytesRead uint64 // application bytes
BytesRedundant uint64 // stream bytes sent again as redundant copies
NoEffectBudget int64
// EventsDropped counts the events NextEvent's queue dropped because
// nobody read them in time.
EventsDropped uint64
}
ConnectionStats are transport counters.
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 DuplicateOptions ¶ added in v1.3.0
type DuplicateOptions struct {
// LocalID and PeerID are the application identities of the two
// endpoints (the same byte strings at both ends), when it has them.
LocalID, PeerID []byte
// Rejoin: when this endpoint dialed the losing session and the
// survivor uses multipath, Dial the route again and join it to the
// survivor (in the background; a hint).
Rejoin bool
Dial func(ctx context.Context) (PipeIO, error)
}
DuplicateOptions are the inputs of ResolveDuplicate.
type DuplicateResult ¶ added in v1.3.0
DuplicateResult reports a resolution.
func ResolveDuplicate ¶ added in v1.3.0
func ResolveDuplicate(s1, s2 *Conn, opts *DuplicateOptions) (DuplicateResult, error)
ResolveDuplicate applies the rule of EXTENSIONS.md 11 to two established sessions that connect the same two endpoints and were dialed by different endpoints: it returns the survivor and starts draining the other session (GOAWAY, no new streams, close with NO_ERROR once its streams have ended). It changes nothing when the sessions have the same dialer or no input decides.
type EarlyClientCarrier ¶ added in v1.3.0
type EarlyClientCarrier interface {
// EarlyAccepted blocks until the handshake decided: true when the
// server accepted the early data.
EarlyAccepted(ctx context.Context) (bool, error)
// RestartEarly returns the pipe's byte stream as it stands after the
// handshake (on QUIC the bootstrap stream opened again).
RestartEarly(ctx context.Context) (io.ReadWriteCloser, error)
}
EarlyClientCarrier is the optional capability of a client carrier that sends early data. The halves of the bootstrap PipeIO implement it.
type EarlyData ¶ added in v1.3.0
type EarlyData struct {
// ZmuxPeer declares the peer a zmux endpoint (client only).
ZmuxPeer bool
// Replayable allows carrier early data (TLS 1.3, QUIC 0-RTT): on a
// client together with Remembered, on a server to accept and mark it.
Replayable bool
// 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
}
EarlyData lets a client send stream data before the server's transport parameters arrive (SPEC.md 6.1.2). With either form, Start, Client and Dial return at once and ConnectionState().Established stays false until the parameters arrive.
ZmuxPeer: the client knows the server is a zmux endpoint and writes its first streams on the bootstrap carrier right away, within the floor values every zmux endpoint grants. Nothing is replayable.
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: streams opened in it are replayable until the handshake completes.
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
// Pipe is the pipe ID of a pipe event.
Pipe uint64
// Priority is the tier (EventPipePriorityChanged,
// EventTierSaturation); Weight the pipe's weight
// (EventPipePriorityChanged).
Priority uint64
Weight uint64
// Reason of EventJoinAuthFailed.
Reason string
// GoAway of EventGoAwayReceived.
GoAway *GoAway
// SmoothedRTT and DeliveryRate (bytes/s) of EventPipeQualityChanged;
// DeliveryRate is also the capacity of EventCapacityBelow and
// EventCapacityRestored.
SmoothedRTT time.Duration
DeliveryRate float64
}
Event is a session event, as NextEvent and Tracer.Event report it. Kind says which of the other fields are set (see EventKind).
type EventKind ¶ added in v1.3.0
type EventKind uint8
EventKind is the kind of a session event. The comment of each kind names the Event fields it sets; the other fields are zero.
const ( // EventPipeAdded reports that a local outbound pipe direction appeared // (Pipe, Direction). EventPipeAdded EventKind = iota + 1 // EventPipeJoined reports that an outbound pipe direction became active // (Pipe, Direction). EventPipeJoined // EventPipeSuspect reports that an outbound pipe direction stopped making // progress (Pipe, Direction). EventPipeSuspect // EventPipeRecovered reports that a suspect outbound direction is active // again (Pipe, Direction). EventPipeRecovered // EventPipeFailed reports that an outbound pipe direction failed (Pipe, // Direction). EventPipeFailed // EventPipeClosed reports that a pipe direction ended; DirBidirectional // when the whole attachment was retired (Pipe, Direction). EventPipeClosed // EventPipePriorityChanged reports that the effective tier, standby state // or weight of an outbound pipe changed (Pipe, Priority, Standby, Weight). EventPipePriorityChanged // EventTierSaturation reports that the usable pipes of a tier became // saturated or stopped being so (Priority, Saturated). EventTierSaturation // EventJoinAuthFailed reports that a join failed authentication (Reason: // "mac" or "mac_carrier_bound"). 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 // multipath but no join secret is available, so no pipe can join (no // fields). EventJoinSecurityUnavailable // EventPipeQualityChanged reports that an outbound pipe left its // QualityBand (Pipe, SmoothedRTT, DeliveryRate). EventPipeQualityChanged // EventCapacityBelow reports that the outbound capacity fell below the // CapacityFloor (DeliveryRate: the capacity). EventCapacityBelow // EventCapacityRestored reports that the outbound capacity is back above // the CapacityFloor (DeliveryRate: the capacity). EventCapacityRestored )
type Framing ¶ added in v1.3.0
type Framing uint8
Framing is a carrier's record framing (SPEC.md 3.1, 3.4).
type GoAway ¶ added in v1.3.0
type GoAway struct {
MaxBidi, MaxUni uint64
ErrorCode ApplicationErrorCode
}
GoAway are the watermarks of a received GOAWAY.
type HandshakeTimeoutError ¶ added in v1.3.0
type HandshakeTimeoutError struct{}
HandshakeTimeoutError reports that the peer's transport parameters did not arrive within Config.HandshakeTimeout. It matches ErrHandshakeTimeout, net.ErrClosed and os.ErrDeadlineExceeded.
func (*HandshakeTimeoutError) Error ¶ added in v1.3.0
func (e *HandshakeTimeoutError) Error() string
Error describes the timeout.
func (*HandshakeTimeoutError) Is ¶ added in v1.3.0
func (e *HandshakeTimeoutError) Is(t error) bool
Is matches ErrHandshakeTimeout, net.ErrClosed and os.ErrDeadlineExceeded.
func (*HandshakeTimeoutError) Timeout ¶ added in v1.3.0
func (e *HandshakeTimeoutError) Timeout() bool
Timeout reports true.
type IdleTimeoutError ¶ added in v1.3.0
type IdleTimeoutError struct{ Remote bool }
IdleTimeoutError reports the idle timeout; Remote when the peer's timer expired. It matches ErrIdleTimeout, net.ErrClosed and os.ErrDeadlineExceeded.
func (*IdleTimeoutError) Error ¶ added in v1.3.0
func (e *IdleTimeoutError) Error() string
Error describes the timeout.
func (*IdleTimeoutError) Is ¶ added in v1.3.0
func (e *IdleTimeoutError) Is(t error) bool
Is matches ErrIdleTimeout, net.ErrClosed and os.ErrDeadlineExceeded.
func (*IdleTimeoutError) Timeout ¶ added in v1.3.0
func (e *IdleTimeoutError) Timeout() bool
Timeout reports true.
type JoinHint ¶ added in v1.3.0
type JoinHint struct {
// Join is the Zmux-Pipe-Join header: an out-of-band PIPE_JOIN.
Join string
// Pair is the Zmux-Pipe-Pair header: the pairing token of a split
// bootstrap (SPEC.md 6.1.1); Uplink says which half this carrier is.
Pair string
Uplink bool
// Source identifies the client for the per-source limit (default: the
// carrier's remote address).
Source string
}
JoinHint is what a carrier's request said out of band (HTTP headers).
type Lease ¶ added in v1.3.0
type Lease[C comparable] struct { // Conn is the connection to open the pipe on. Conn C // FateGroup is the connection's fate group (set it as the PipeIO's). FateGroup uint64 // contains filtered or unexported fields }
Lease is one pipe's use of a pooled connection; the adapter releases it when the pipe ends.
type Limiter ¶ added in v1.3.0
type Limiter interface {
// Ready waits until at least min bytes (or the limiter's burst, if
// less) are allowed and returns the allowance, at most max.
Ready(ctx context.Context, min, max int) (int, error)
// TryReady returns the allowance now, 0 when it would have to wait.
TryReady(max int) int
// Charge accounts n bytes actually forwarded.
Charge(n int)
}
Limiter lets an external limiter, budget or meter act on bytes that zmux forwards itself (Splice, datagrams). zmux calls it outside every session lock.
type Listener ¶ added in v1.3.0
type Listener struct {
// contains filtered or unexported fields
}
Listener is the server side of zmux: it accepts sessions and the pipes that join them (MULTIPATH.md 5.4, 5.5), so it is the way to serve clients that use multipath, resume or split carriers. Serve feeds it the connections of a net.Listener (TCP, or TLS with tls.NewListener); HandlePipe feeds it any other carrier, and ServeHTTP HTTP carriers. Accept returns the sessions it started:
l := zmux.NewListener(&zmux.ListenerConfig{Config: cfg})
go l.Serve(ctx, ln)
for {
conn, err := l.Accept(ctx)
if err != nil {
return err
}
go handle(conn)
}
Close stops accepting; Shutdown also closes the accepted sessions gracefully. Its lock is a leaf: it never takes a session lock while held.
func NewListener ¶ added in v1.3.0
func NewListener(cfg *ListenerConfig) *Listener
NewListener returns a listener; feed it carriers with Serve, HandlePipe or ServeHTTP. cfg may be nil. It panics if cfg.InstanceID is longer than MaxInstanceIDLen.
func (*Listener) Close ¶ added in v1.3.0
Close stops accepting: Accept and Serve return net.ErrClosed, new carriers are refused and the memory-pressure watcher stops. It does not block, and sessions already started continue; Shutdown ends them too.
func (*Listener) HandlePipe ¶ added in v1.3.0
HandlePipe classifies a new carrier by its first record (or its hint) and starts a session on it, attaches it to a session as a pipe, or closes it. It blocks for the lifetime of the pipe, so that an HTTP handler stays alive; when ctx ends the pipe is aborted.
func (*Listener) MemoryUsed ¶ added in v1.3.0
MemoryUsed reports the sum charged to the listener's memory budget.
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. For TLS, pass a listener made by tls.NewListener. Serve closes ln when it returns: when ln.Accept fails, when ctx ends (ctx's error), or when the listener is closed (net.ErrClosed). Cancelling ctx also aborts the carriers Serve handed over, ending their pipes; Shutdown or Close leave them to the sessions.
func (*Listener) ServeHTTP ¶ added in v1.3.0
func (l *Listener) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP hands an HTTP request to the listener as a carrier: a GET is a downlink (the response body), a request with a pairing token and a body is an uplink, any other request with a body carries both directions (full duplex). It returns when the pipe ends.
func (*Listener) Shutdown ¶ added in v1.3.0
Shutdown closes the listener and then shuts down every session it started, accepted or not, with Conn.Shutdown(ctx, code, msg) in parallel: each sends GOAWAY, lets its open streams finish and closes. It returns when every session has ended, or with ctx's error once ctx ends (the remaining sessions are then closed at once).
type ListenerConfig ¶ added in v1.3.0
type ListenerConfig struct {
// Config is the configuration of the sessions it accepts.
Config *Config
// MaxSuspended bounds the suspended sessions it holds (1024); the
// longest-suspended are closed with ZMUX_RESUME_TIMEOUT.
MaxSuspended int
// MaxPendingPerSource bounds the carriers of one source that have not
// delivered their first record (8).
MaxPendingPerSource int
// FirstRecordTimeout closes a carrier whose first record does not
// arrive in time (2 s).
FirstRecordTimeout time.Duration
// Backlog is the number of sessions waiting for Accept (128); a new
// session beyond it is refused.
Backlog int
// InstanceID is encoded at the start of every session locator, for
// load-balancer stickiness; random bytes fill the rest of the 16-byte
// locator. At most MaxInstanceIDLen bytes.
InstanceID []byte
// MemoryBudget bounds the sum over the listener's sessions of buffered
// receive data, retained data and session window growth (1 GiB;
// negative: unlimited). It replaces the sessions' own
// Config.MemoryBudget. Above it sessions grant no new credit, refuse
// new peer streams, new sessions and pipes are refused, and suspended
// sessions are closed, the largest first; normal operation resumes
// below three quarters of it.
MemoryBudget int64
// OnMemoryPressure is called 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 uint64)
}
ListenerConfig configures a Listener. The zero value of every field selects its default.
type MessageReader ¶ added in v1.3.0
type MessageReader interface {
// ReadMessage returns the next whole message.
ReadMessage() ([]byte, error)
}
MessageReader is the receiving half of a message-framed carrier.
type MessageWriter ¶ added in v1.3.0
type MessageWriter interface {
// WriteMessage writes one whole message.
WriteMessage(p []byte) error
}
MessageWriter is the sending half of a message-framed carrier.
type 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: Pipe is an index into the pipes, Bytes the bytes it covers (0: until invalidated); Wait holds the direction until the session's next input.
type PickPipe ¶ added in v1.3.0
type PickPipe struct {
Pipe uint64
State string
SRTT time.Duration
RTTVar time.Duration
Rate uint64 // bytes/s
Unsent uint64
InFlight uint64
Priority uint64
Weight uint64
Writable bool
Standby bool
Saturated bool
Probation bool
Eligible bool // under tier gating: the built-in policies choose among these
}
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).
func (*Pipe) ClearSendPriority ¶ added in v1.3.0
ClearSendPriority returns the outbound tier to the peer's request.
func (*Pipe) ClearSendStandby ¶ added in v1.3.0
ClearSendStandby returns the standby flag to the peer's request.
func (*Pipe) Close ¶ added in v1.3.0
Close removes the pipe gracefully: PIPE_ABANDON(NO_ERROR) and drain (MULTIPATH.md 8.2). It does not block; the pipe's end is reported by NextEvent.
func (*Pipe) 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) SetProbation ¶ added in v1.3.0
SetProbation sets the base of the pipe's probation; 0 disables it, a negative value returns to the session's default.
func (*Pipe) SetQualityBand ¶ added in v1.3.0
func (p *Pipe) SetQualityBand(b QualityBand) error
SetQualityBand sets the band of this pipe.
func (*Pipe) SetReceivePriority ¶ added in v1.3.0
SetReceivePriority asks the peer to use v for its outbound direction; the request is sent at once as PIPE_STATUS (once the pipe is ACTIVE).
func (*Pipe) SetReceiveStandby ¶ added in v1.3.0
SetReceiveStandby asks the peer to treat its outbound direction as standby (or not).
func (*Pipe) SetSendPriority ¶ added in v1.3.0
SetSendPriority sets the tier of the local outbound direction; it wins over the peer's request. Nothing is sent.
func (*Pipe) SetSendStandby ¶ added in v1.3.0
SetSendStandby makes the local outbound direction standby (or not).
type PipeAuth ¶ added in v1.3.0
type PipeAuth struct {
// PSK is a pre-shared key of at least 16 bytes.
PSK []byte
// TLS asserts that pipe 0's TLS 1.3 handshake terminates at the peer.
TLS bool
// AllowInsecure allows joins without a secret (tests, protected
// networks). It must not be combined with PSK.
AllowInsecure bool
}
PipeAuth selects the secret sources of joins (MULTIPATH.md 10.1).
type PipeIO ¶ added in v1.3.0
type PipeIO struct {
R io.ReadCloser
W io.WriteCloser
Framing Framing
// Label names the pipe in statistics.
Label string
// FateGroup is the carrier's own fate group (a carrier pool's pipes on
// one connection share one), used when PipeOptions.FateGroup is 0.
FateGroup uint64
}
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:
- interface{ Abort(error) } on W: used instead of Close when a pipe fails;
- interface{ CloseWrite() error } on W: graceful end of the write side;
- interface{ ConnectionState() tls.ConnectionState }: a TLS carrier (records built at 16382 bytes, exporter for PipeAuth.TLS);
- interface{ CarrierConn() any } and interface{ OpenLane(ctx) (io.WriteCloser, error) }: lanes;
- interface{ RestartEarly(ctx) (io.ReadWriteCloser, error) }: carrier early data.
A half's Close must interrupt a blocked Read or Write.
func HTTPPipe ¶ added in v1.3.0
func HTTPPipe(ctx context.Context, client *http.Client, url string, h http.Header, dir Direction) (PipeIO, error)
HTTPPipe opens a carrier over an HTTP request: dir DirBidirectional sends the request body up and reads the response body (HTTP/2, HTTP/3, or an HTTP/1.1 server with full duplex); DirSendOnly is a POST whose body is the uplink; DirReceiveOnly is a GET whose response body is the downlink. h may carry the Zmux-Pipe-Join value of a Reservation. The request lives until the pipe ends.
func HTTPSplitPipe ¶ added in v1.3.0
func HTTPSplitPipe(ctx context.Context, client *http.Client, url string, h http.Header) (PipeIO, error)
HTTPSplitPipe opens a split bootstrap over two requests, a POST uplink and a GET downlink, paired by a random pairing token (SPEC.md 6.1.1). The carriers must be confidential end to end (TLS to the server).
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 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).
type PipeOptions ¶ added in v1.3.0
type PipeOptions struct {
// SendPriority is the tier of the local outbound direction (lower is
// preferred). nil: the peer's request, else tier 0.
SendPriority *uint64
// SendStandby makes the local outbound direction carry data only on
// failover. nil: the peer's request, else active.
SendStandby *bool
// Weight is the share for SpreadRoundRobin and the factor of
// SpreadRateWeighted. nil: 1; 0 excludes the pipe unless every
// candidate has 0.
Weight *uint64
// Probation is the base of the pipe's probation. nil: the session's;
// 0 disables it.
Probation *time.Duration
// Label names the pipe in statistics.
Label string
// ReceivePriority is the tier requested for the peer's outbound
// direction (zero: tier 0).
ReceivePriority uint64
// FateGroup groups pipes that share a path; a pipe that replaces a
// failed one on the same path reuses its fate group. 0: the carrier's
// PipeIO.FateGroup, else none (an independent path).
FateGroup uint64
// SuspectFloor (at least 50 ms) and DeadTimeout (at least 1 s) of the
// pipe; 0 uses the session's.
SuspectFloor time.Duration
DeadTimeout time.Duration
// Direction from the local endpoint: DirBidirectional (the zero
// value), DirSendOnly (an uplink) or DirReceiveOnly (a downlink).
Direction Direction
// ReceiveStandby asks the peer to make its outbound direction standby
// (zero: active).
ReceiveStandby bool
// CarrierBound ties the join token to the new carrier's TLS 1.3
// handshake (MULTIPATH.md 10.5); the carrier must be a TLS connection
// that terminates at the peer.
CarrierBound bool
}
PipeOptions are the options of an attachment. The zero value is a bidirectional pipe that follows the peer's priority requests and the session's defaults.
The Send fields are pointers because nil has its own meaning: the local outbound direction then follows the peer's request (PIPE_STATUS); a set value wins over it. The Receive fields are plain values because they are always sent: the PIPE_JOIN carries a request for the peer's outbound direction, so the zero values ask for tier 0, not standby.
type PipePool ¶ added in v1.3.0
type PipePool struct {
// Dial opens a carrier of the path.
Dial func(ctx context.Context) (PipeIO, error)
// Count is the number of usable pipes to keep (default 1).
Count int
// Options of the pipes the pool joins.
Options PipeOptions
// Rotate replaces pipes that carried MaxBytes or are MaxAge old.
Rotate Rotation
// Backoff bounds the redial backoff (from 1 s, at most 60 s).
MinBackoff, MaxBackoff time.Duration
}
PipePool keeps pipes of one path up.
type PipeStats ¶ added in v1.3.0
type PipeStats struct {
ID uint64
Label string
State string // joining, active, suspect, draining, failed, closed
InState string // opening, open, ended
AttachedFor time.Duration
SuspectCount uint64
FailureCount uint64
SendPriority uint64
SendPrioritySource string // local, peer, default
StandbySource string
ReceivePriority uint64
StatusSequence uint64
PeerRequest *PeerRequest
Weight uint64
ProbationUntil time.Time // zero outside probation
SmoothedRTT time.Duration // estimate
MinRTT time.Duration // estimate
RTTVar time.Duration // estimate
OWD time.Duration // estimate
DeliveryRate float64 // bytes/s, estimate
RTTSource string // ack, kernel, ping
QueuedBytes uint64
QueueDelay time.Duration // estimate
BytesInFlight uint64
BytesSent uint64
BytesReceived uint64
BytesAcked uint64
RecordsSent uint64
RecordsReceived uint64
BytesReinjected uint64
BytesOpportunistic uint64
PingsSent uint64
SinceLastAck time.Duration
SinceLastReceive time.Duration
Lanes int
Direction Direction
Revalidating bool
Standby bool // with StandbySource
ReceiveStandby bool
Eligible bool
Writable bool
Saturated bool
}
PipeStats is a snapshot of one attachment, taken under the session lock.
type PipesLostError ¶ added in v1.3.0
type PipesLostError struct{ LastPipeErr error }
PipesLostError reports that the carrier failed or every pipe of a direction was lost without resume. It matches ErrPipesLost and net.ErrClosed and unwraps to the error of the last pipe lost, if any.
func (*PipesLostError) Error ¶ added in v1.3.0
func (e *PipesLostError) Error() string
Error describes the loss.
func (*PipesLostError) Is ¶ added in v1.3.0
func (e *PipesLostError) Is(t error) bool
Is matches ErrPipesLost and net.ErrClosed.
func (*PipesLostError) Unwrap ¶ added in v1.3.0
func (e *PipesLostError) Unwrap() error
Unwrap returns LastPipeErr.
type PoolLimits ¶ added in v1.3.0
type PoolLimits struct {
// MaxPipesPerConnection bounds the pipes on a connection at once
// (0: 8).
MaxPipesPerConnection int
// MaxPipesPerConnectionLifetime bounds the pipes a connection carries
// over its life (0: unlimited).
MaxPipesPerConnectionLifetime int
// MaxConnectionAge stops giving pipes to a connection this old (0:
// unlimited).
MaxConnectionAge time.Duration
}
PoolLimits bound how a carrier pool uses each underlying connection. The zero value selects the defaults.
type QualityBand ¶ added in v1.3.0
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. A zero RTT or RateRatio turns that half off, so the zero QualityBand reports nothing; a zero MinInterval means 1 s, a negative one no minimum.
type ReceiveStream ¶ added in v1.3.0
type ReceiveStream struct {
// contains filtered or unexported fields
}
ReceiveStream is the receiving part of a stream.
func (*ReceiveStream) CancelRead ¶ added in v1.3.0
func (s *ReceiveStream) CancelRead(code StreamErrorCode)
CancelRead stops reading.
func (*ReceiveStream) Preamble ¶ added in v1.3.0
func (s *ReceiveStream) Preamble() []byte
Preamble returns the peer's OPEN_INFO.
func (*ReceiveStream) PreambleTLVs ¶ added in v1.3.0
func (s *ReceiveStream) PreambleTLVs() []TLV
PreambleTLVs returns the application TLVs of the peer's preamble.
func (*ReceiveStream) Read ¶ added in v1.3.0
func (s *ReceiveStream) Read(p []byte) (int, error)
Read reads stream data.
func (*ReceiveStream) ReadChunk ¶ added in v1.3.0
ReadChunk returns up to max bytes without copying.
func (*ReceiveStream) Reject ¶ added in v1.3.0
func (s *ReceiveStream) Reject()
Reject declines the stream before reading it.
func (*ReceiveStream) Replayable ¶ added in v1.3.0
func (s *ReceiveStream) Replayable() bool
Replayable reports whether the stream arrived as carrier early data.
func (*ReceiveStream) SetPeerPriority ¶ added in v1.3.0
func (s *ReceiveStream) SetPeerPriority(urgency Urgency, incremental bool) error
SetPeerPriority asks the peer to schedule the stream so, as Stream.SetPeerPriority.
func (*ReceiveStream) SetReadDeadline ¶ added in v1.3.0
func (s *ReceiveStream) SetReadDeadline(t time.Time) error
SetReadDeadline sets the read deadline.
func (*ReceiveStream) SetReceiveWindow ¶ added in v1.3.0
func (s *ReceiveStream) SetReceiveWindow(initial, max uint64)
SetReceiveWindow sets the stream's initial and maximum receive window.
func (*ReceiveStream) StreamID ¶ added in v1.3.0
func (s *ReceiveStream) StreamID() StreamID
StreamID of a receiving part.
type Reservation ¶ added in v1.3.0
type Reservation struct {
// contains filtered or unexported fields
}
Reservation is a pipe reserved for an out-of-band join (MULTIPATH.md 5.3): send Header() with the carrier's request as the Zmux-Pipe-Join header, then Attach the carrier.
func (*Reservation) Attach ¶ added in v1.3.0
Attach binds the carrier of the reserved pipe and waits until the join is confirmed (see AddPipe).
func (*Reservation) Cancel ¶ added in v1.3.0
func (r *Reservation) Cancel()
Cancel abandons the reservation.
func (*Reservation) Header ¶ added in v1.3.0
func (r *Reservation) Header() string
Header returns the Zmux-Pipe-Join header value (base64url of the PIPE_JOIN frame, without padding).
type ResumeTimeoutError ¶ added in v1.3.0
type ResumeTimeoutError struct{ LastPipeErr error }
ResumeTimeoutError reports that a suspended session found no pipe within the resume grace period. It matches ErrResumeTimeout and net.ErrClosed and unwraps to the error of the last pipe lost, if any.
func (*ResumeTimeoutError) Error ¶ added in v1.3.0
func (e *ResumeTimeoutError) Error() string
Error describes the timeout.
func (*ResumeTimeoutError) Is ¶ added in v1.3.0
func (e *ResumeTimeoutError) Is(t error) bool
Is matches ErrResumeTimeout and net.ErrClosed.
func (*ResumeTimeoutError) Unwrap ¶ added in v1.3.0
func (e *ResumeTimeoutError) Unwrap() error
Unwrap returns LastPipeErr.
type 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
Rotation replaces pipes before a lifetime limit: when a pipe has carried MaxBytes in either direction or is MaxAge old (each reduced by a random fraction of up to Jitter), a replacement is dialled and joined, and the old pipe is closed gracefully once the replacement is usable (make before break).
type Scheduler ¶ added in v1.3.0
type Scheduler interface {
// contains filtered or unexported methods
}
Scheduler is a scheduling policy of a multipath session. The built-in policies are returned by Affinity, SessionAffinity, SpreadETA, SpreadRoundRobin and SpreadRateWeighted.
Example ¶
ExampleScheduler sets a session's scheduling policy in its Config and changes it while the session runs; it applies once there are several pipes.
package main
import (
"context"
"fmt"
"net"
"time"
"github.com/zmuxio/zmux-go"
)
// sessions returns a client and a server session over an in-memory carrier.
func sessions(ctx context.Context, ccfg, scfg *zmux.Config) (client, server *zmux.Conn, err error) {
a, b := net.Pipe()
ch := make(chan error, 1)
go func() {
var err error
server, err = zmux.Server(ctx, b, scfg)
ch <- err
}()
client, err = zmux.Client(ctx, a, ccfg)
if serr := <-ch; err == nil {
err = serr
}
if err != nil {
if client != nil {
_ = client.Close()
}
if server != nil {
_ = server.Close()
}
return nil, nil, err
}
return client, server, nil
}
// closeBoth closes both sessions and waits for their ends.
func closeBoth(a, b *zmux.Conn) {
_ = a.Close()
_ = b.Close()
_ = a.Wait()
_ = b.Wait()
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
cfg := &zmux.Config{Scheduler: zmux.SessionAffinity()} // one active pipe per tier
client, server, err := sessions(ctx, cfg, nil)
if err != nil {
fmt.Println(err)
return
}
defer closeBoth(client, server)
// Share chunks by weight times measured rate from now on.
client.SetScheduler(zmux.SpreadRateWeighted())
fmt.Println(len(client.PipeStats()))
}
Output: 1
func Affinity ¶ added in v1.3.0
func Affinity() Scheduler
Affinity binds each stream direction to one pipe (the default).
func SessionAffinity ¶ added in v1.3.0
func SessionAffinity() Scheduler
SessionAffinity uses one active pipe per tier.
func SpreadETA ¶ added in v1.3.0
func SpreadETA() Scheduler
SpreadETA sends every chunk on the pipe with the earliest arrival.
func SpreadRateWeighted ¶ added in v1.3.0
func SpreadRateWeighted() Scheduler
SpreadRateWeighted shares chunks by weight times measured rate.
func SpreadRoundRobin ¶ added in v1.3.0
func SpreadRoundRobin() Scheduler
SpreadRoundRobin shares chunks by the pipes' weights.
type SchedulerParams ¶ added in v1.3.0
type SchedulerParams struct {
SuspectFloor time.Duration // 250 ms, at least 50 ms
DeadTimeout time.Duration // 0: default
Probation *time.Duration
OverflowDelay time.Duration // 1 s
StandbyProbe time.Duration // 1 s; negative: the probe interval
ProbeInterval time.Duration // 15 s; negative: off
NoRedundancy bool // redundancy "off"
SpreadChunk int // 16 KiB
}
SchedulerParams tune multipath scheduling and failure detection; the zero value of every field selects its default.
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) 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) ReadFrom ¶ added in v1.3.0
func (s *SendStream) ReadFrom(r io.Reader) (int64, error)
ReadFrom implements io.ReaderFrom.
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.
func (*SendStream) SetPriority ¶ added in v1.3.0
func (s *SendStream) SetPriority(urgency Urgency, incremental bool)
SetPriority sets the local scheduling priority, as Stream.SetPriority.
func (*SendStream) SetRedundant ¶ added in v1.3.0
func (s *SendStream) SetRedundant(on bool)
SetRedundant turns redundant sending on or off (multipath).
func (*SendStream) SetReliableBoundary ¶ added in v1.3.0
func (s *SendStream) SetReliableBoundary()
SetReliableBoundary marks the data written so far as delivered.
func (*SendStream) SetScheduler ¶ added in v1.3.0
func (s *SendStream) SetScheduler(p Scheduler)
SetScheduler sets the stream's own scheduling policy (nil: the session's).
func (*SendStream) SetSendBuffer ¶ added in v1.3.0
func (s *SendStream) SetSendBuffer(n uint64)
SetSendBuffer bounds the stream's written-but-unreleased bytes.
func (*SendStream) SetWriteDeadline ¶
func (s *SendStream) SetWriteDeadline(t time.Time) error
SetWriteDeadline sets the write deadline.
func (*SendStream) 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) 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 SpliceDirection ¶ added in v1.3.0
type SpliceDirection struct {
Bytes uint64 // stream bytes forwarded
DatagramBytes uint64 // datagram bytes forwarded
DatagramsDropped uint64
// End is how the direction ended: nil for a FIN, else the reset,
// stop, session error or cancellation that ended it.
End error
}
SpliceDirection is the result of one direction of a splice.
type SpliceOptions ¶ added in v1.3.0
type SpliceOptions struct {
// Chunk is the most one direction holds at once (64 KiB).
Chunk int
// AtoB and BtoA limit the two directions (nil: none).
AtoB, BtoA Limiter
}
SpliceOptions configure Splice.
type SpliceResult ¶ added in v1.3.0
type SpliceResult struct {
AtoB, BtoA SpliceDirection
}
SpliceResult is the result of Splice.
func Splice ¶ added in v1.3.0
func Splice(ctx context.Context, a, b *Stream, opts *SpliceOptions) (SpliceResult, error)
Splice forwards two bidirectional streams into each other until both directions have ended: what arrives on a is sent on b and what arrives on b is sent on a, a chunk at a time, without copying and only within the receiving side's credit, so backpressure crosses the relay hop by hop. Ends travel across: FIN finishes the other side, a reset resets it with its code after the bytes below its Reliable Size, a stop stops the upstream, a lost session fails the other side with ZMUX_CARRIER_FAILED, and cancelling ctx ends both with code 0.
Example ¶
ExampleSplice relays a stream of one session into a stream of another, as a proxy does: data, ends and backpressure cross without a copy.
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// client <-> relay (session A); relay <-> backend (session B).
client, relayA, err := sessions(ctx, nil, nil)
if err != nil {
fmt.Println(err)
return
}
defer closeBoth(client, relayA)
relayB, backend, err := sessions(ctx, nil, nil)
if err != nil {
fmt.Println(err)
return
}
defer closeBoth(relayB, backend)
go echo(ctx, backend)
res := make(chan zmux.SpliceResult, 1)
go func() {
in, err := relayA.AcceptStream(ctx)
if err != nil {
return
}
out, err := relayB.OpenStreamSync(ctx)
if err != nil {
in.CancelRead(zmux.StreamCancelled)
in.CancelWrite(zmux.StreamCancelled)
return
}
r, _ := zmux.Splice(ctx, in, out, nil)
res <- r
}()
reply, err := roundTrip(ctx, client, "through the relay")
if err != nil {
fmt.Println(err)
return
}
r := <-res
fmt.Println(reply)
fmt.Println(r.AtoB.Bytes, r.BtoA.Bytes, r.AtoB.End, r.BtoA.End)
Output: through the relay 17 17 <nil> <nil>
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.
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) 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) 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) PreambleTLVs ¶ added in v1.3.0
PreambleTLVs returns the application TLVs of the peer's preamble.
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 max 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.
func (*Stream) ReceiveDatagram ¶ added in v1.3.0
ReceiveDatagram returns the next stream datagram and its context identifier.
func (*Stream) Reject ¶ added in v1.3.0
func (s *Stream) Reject()
Reject declines an accepted stream before reading it: both directions end with ZMUX_REJECTED.
func (*Stream) Replayable ¶ added in v1.3.0
Replayable reports whether the stream's opening frame arrived as carrier early data before the handshake completed (treat its request as one an attacker may have repeated).
func (*Stream) SendCapacity ¶ added in v1.3.0
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.
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 (0 leaves a value; at least 16 KiB).
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 session's).
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) StreamID ¶
StreamID returns the identifier; before the first frame it pins it and the opening frame is sent at once (SPEC.md 7.2).
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) WaitSendCapacity ¶ added in v1.3.0
WaitSendCapacity waits until SendCapacity is at least min (or above 0 while nothing is unsent) and returns it.
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
Remote bool
// ReliableSize is the RESET_STREAM_AT Reliable Size of a reset.
ReliableSize uint64
}
StreamError is a stream ended by the peer: a reset on reads, a STOP_SENDING on writes.
Example ¶
ExampleStreamError shows a stream canceled with a conventional code: the peer sees that code.
package main
import (
"context"
"errors"
"fmt"
"io"
"net"
"time"
"github.com/zmuxio/zmux-go"
)
// sessions returns a client and a server session over an in-memory carrier.
func sessions(ctx context.Context, ccfg, scfg *zmux.Config) (client, server *zmux.Conn, err error) {
a, b := net.Pipe()
ch := make(chan error, 1)
go func() {
var err error
server, err = zmux.Server(ctx, b, scfg)
ch <- err
}()
client, err = zmux.Client(ctx, a, ccfg)
if serr := <-ch; err == nil {
err = serr
}
if err != nil {
if client != nil {
_ = client.Close()
}
if server != nil {
_ = server.Close()
}
return nil, nil, err
}
return client, server, nil
}
// closeBoth closes both sessions and waits for their ends.
func closeBoth(a, b *zmux.Conn) {
_ = a.Close()
_ = b.Close()
_ = a.Wait()
_ = b.Wait()
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
client, server, err := sessions(ctx, nil, nil)
if err != nil {
fmt.Println(err)
return
}
defer closeBoth(client, server)
st, err := client.OpenStreamSync(ctx)
if err != nil {
fmt.Println(err)
return
}
if _, err := st.Write([]byte("x")); err != nil {
fmt.Println(err)
return
}
peer, err := server.AcceptStream(ctx)
if err != nil {
fmt.Println(err)
return
}
st.CancelWrite(zmux.StreamCancelled)
_, err = io.ReadAll(peer)
var se *zmux.StreamError
if errors.As(err, &se) {
switch se.ErrorCode {
case zmux.StreamNoError:
fmt.Println("no error")
case zmux.StreamCancelled:
fmt.Println("cancelled by the peer")
case zmux.StreamRejected, zmux.StreamCarrierFailed:
fmt.Println("rejected or carrier failed")
default:
fmt.Printf("application code %#x\n", uint64(se.ErrorCode))
}
}
}
Output: cancelled by the peer
func (*StreamError) Error ¶ added in v1.3.0
func (e *StreamError) Error() string
Error describes the reset or STOP_SENDING.
func (*StreamError) Is ¶ added in v1.3.0
func (e *StreamError) Is(t error) bool
Is matches ErrRejected for a peer's ZMUX_REJECTED: the peer did not process the stream, which can be retried (IsRetryable).
type StreamErrorCode ¶ added in v1.3.0
type StreamErrorCode uint64
StreamErrorCode is an application error code of a stream.
const ( StreamNoError StreamErrorCode = 0 StreamCancelled StreamErrorCode = 0x5a4d0001 StreamRejected StreamErrorCode = 0x5a4d0002 StreamCarrierFailed StreamErrorCode = 0x5a4d0003 )
Application error-code conventions (EXTENSIONS.md Section 7).
type StreamID ¶ added in v1.3.0
type StreamID int64
StreamID is a stream identifier (RFC 9000 Section 2.1).
type StreamLimitReachedError ¶ added in v1.3.0
type StreamLimitReachedError struct{}
StreamLimitReachedError reports that no stream credit is available now (OpenStream); OpenStreamSync waits for credit instead.
func (*StreamLimitReachedError) Error ¶ added in v1.3.0
func (e *StreamLimitReachedError) Error() string
Error describes the condition.
func (*StreamLimitReachedError) Temporary ¶ added in v1.3.0
func (e *StreamLimitReachedError) Temporary() bool
Temporary reports that credit may arrive later.
type Tracer ¶ added in v1.3.0
type Tracer struct {
// Established: the peer's transport parameters were processed.
Established func()
// Event: a pipe or session event (as NextEvent reports them).
Event func(Event)
// Dropped: events lost to overflow since the previous call.
Dropped func(count uint64)
// Closed: the session ended; nothing follows.
Closed func(err error)
}
Tracer receives session events. Its functions run serially and in order on a goroutine of the session, never under a lock; the session never waits for them: a bounded queue holds events, and on overflow the events other than Closed are dropped and counted.
type TransportError ¶ added in v1.3.0
type TransportError struct {
Remote bool
ErrorCode TransportErrorCode
FrameType uint64
ErrorMessage string
// Details are the key=value pairs of the diagnostic line (SPEC.md 4.3).
Details string
}
TransportError is a session closed for a protocol error (0x1c).
Example ¶
ExampleTransportError sorts session ends by their transport error code.
package main
import (
"errors"
"fmt"
"github.com/zmuxio/zmux-go"
)
func main() {
describe := func(err error) string {
var te *zmux.TransportError
if !errors.As(err, &te) {
return "not a transport error"
}
switch te.ErrorCode {
case zmux.TransportNoError:
return "closed without error"
case zmux.TransportProtocolViolation, zmux.TransportFrameEncodingError, zmux.TransportFlowControlError,
zmux.TransportStreamLimitError, zmux.TransportStreamStateError, zmux.TransportFinalSizeError,
zmux.TransportParameterError, zmux.TransportRoleConflict:
return "peer misbehaved: " + te.ErrorCode.String()
case zmux.TransportInternalError, zmux.TransportExcessiveLoad, zmux.TransportConnectionRefused:
return "peer refused or failed: " + te.ErrorCode.String()
case zmux.TransportNoViablePath, zmux.TransportResumeTimeout, zmux.TransportResumeFailed, zmux.TransportIdleTimeout:
return "carriers lost: " + te.ErrorCode.String()
default:
return "other: " + te.ErrorCode.String()
}
}
fmt.Println(describe(&zmux.TransportError{Remote: true, ErrorCode: zmux.TransportProtocolViolation}))
fmt.Println(describe(&zmux.TransportError{Remote: true, ErrorCode: zmux.TransportIdleTimeout}))
}
Output: peer misbehaved: PROTOCOL_VIOLATION carriers lost: ZMUX_IDLE_TIMEOUT
func (*TransportError) Error ¶ added in v1.3.0
func (e *TransportError) Error() string
Error describes the close.
func (*TransportError) Is ¶ added in v1.3.0
func (e *TransportError) Is(t error) bool
Is makes every session termination match net.ErrClosed.
type TransportErrorCode ¶ added in v1.3.0
type TransportErrorCode uint64
TransportErrorCode is a transport error code (SPEC.md Section 10.2).
const ( TransportNoError TransportErrorCode = 0x00 TransportInternalError TransportErrorCode = 0x01 TransportConnectionRefused TransportErrorCode = 0x02 TransportFlowControlError TransportErrorCode = 0x03 TransportStreamLimitError TransportErrorCode = 0x04 TransportStreamStateError TransportErrorCode = 0x05 TransportFinalSizeError TransportErrorCode = 0x06 TransportFrameEncodingError TransportErrorCode = 0x07 TransportParameterError TransportErrorCode = 0x08 TransportProtocolViolation TransportErrorCode = 0x0a TransportNoViablePath TransportErrorCode = 0x10 TransportExcessiveLoad TransportErrorCode = 0x25ff75ef TransportRoleConflict TransportErrorCode = 0x277db2c3 TransportResumeTimeout TransportErrorCode = 0x0eb87167 TransportResumeFailed TransportErrorCode = 0x0f05f74e TransportIdleTimeout TransportErrorCode = 0x2736d55c )
Transport error codes.
func (TransportErrorCode) String ¶ added in v1.3.0
func (c TransportErrorCode) String() string
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
adapter
|
|
|
quicmux
module
|
|
|
internal
|
|
|
conformance
Package conformance runs the executable traces and the wire corpus of the zmux specification against the sans-IO core (TRACES.md).
|
Package conformance runs the executable traces and the wire corpus of the zmux specification against the sans-IO core (TRACES.md). |
|
core
Package core is the sans-IO zmux session.
|
Package core is the sans-IO zmux session. |
|
leakcheck
Package leakcheck verifies that a test leaves no goroutines behind (a standard-library replacement for goleak).
|
Package leakcheck verifies that a test leaves no goroutines behind (a standard-library replacement for goleak). |
|
wire
Package wire encodes and decodes the zmux wire format: QUIC variable-length integers, QMux records, frames, transport parameters and stream preambles.
|
Package wire encodes and decodes the zmux wire format: QUIC variable-length integers, QMux records, frames, transport parameters and stream preambles. |
|
seal
module
|
|
|
zmuxh3
module
|
|
|
zmuxquic
module
|
|
|
zmuxws
module
|