zmux

package module
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Oct 6, 2026 License: Apache-2.0 Imports: 21 Imported by: 2 modules, 1 package

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

zmux-go

zmux-go is the Go implementation of the zmux v1 single-link stream multiplexing protocol.

It exposes:

  • native zmux APIs on *zmux.Conn
  • stable transport-agnostic interfaces: Session, Stream, SendStream, RecvStream
  • native-only interfaces: NativeSession, NativeStream, NativeSendStream, NativeRecvStream
  • a QUIC adapter: github.com/zmuxio/zmux-go/adapter/quicmux

Constructors

Native constructors return *zmux.Conn and expose the full zmux API:

conn, err := zmux.New(rwc, cfg)
client, err := zmux.Client(rwc, cfg)
server, err := zmux.Server(rwc, cfg)

Use New when the transport does not already fix the initiator/responder role. Use Client or Server when the role is already known. Any net.Conn can be passed directly because it satisfies io.ReadWriteCloser.

Stable constructors return Session for code that should work with native zmux and adapters:

session, err := zmux.NewSession(rwc, cfg)
session, err := zmux.ClientSession(rwc, cfg)
session, err := zmux.ServerSession(rwc, cfg)

You can also view an existing native connection through the stable session interface:

native, err := zmux.New(rwc, cfg)
session := zmux.AsSession(native)

Stable Interfaces

These are the interfaces application code should depend on when it needs to handle native zmux sessions and adapters through the same code path.

Session is the stable session surface:

type Session interface {
	io.Closer

	AcceptStream(ctx context.Context) (Stream, error)
	AcceptUniStream(ctx context.Context) (RecvStream, error)

	OpenStream(ctx context.Context) (Stream, error)
	OpenUniStream(ctx context.Context) (SendStream, error)

	OpenStreamWithOptions(ctx context.Context, opts OpenOptions) (Stream, error)
	OpenUniStreamWithOptions(ctx context.Context, opts OpenOptions) (SendStream, error)

	OpenAndSend(ctx context.Context, p []byte) (Stream, int, error)
	OpenAndSendWithOptions(ctx context.Context, opts OpenOptions, p []byte) (Stream, int, error)

	OpenUniAndSend(ctx context.Context, p []byte) (SendStream, int, error)
	OpenUniAndSendWithOptions(ctx context.Context, opts OpenOptions, p []byte) (SendStream, int, error)

	CloseWithError(err error)
	Wait(ctx context.Context) error
	Closed() bool
	State() SessionState
	Stats() SessionStats
}

Stream is the stable bidirectional stream surface:

type Stream interface {
	net.Conn

	StreamID() uint64
	OpenInfo() []byte
	Metadata() StreamMetadata
	UpdateMetadata(update MetadataUpdate) error

	WriteFinal(p []byte) (int, error)
	WritevFinal(parts ...[]byte) (int, error)

	CloseRead() error
	CancelRead(code uint64) error

	CloseWrite() error
	CancelWrite(code uint64) error

	CloseWithError(code uint64, reason string) error
}

SendStream and RecvStream are the stable unidirectional stream surfaces:

type SendStream interface {
	io.Writer
	io.Closer

	StreamID() uint64
	OpenInfo() []byte
	LocalAddr() net.Addr
	RemoteAddr() net.Addr

	Metadata() StreamMetadata
	UpdateMetadata(update MetadataUpdate) error

	WriteFinal(p []byte) (int, error)
	WritevFinal(parts ...[]byte) (int, error)

	CloseWrite() error
	CancelWrite(code uint64) error
	CloseWithError(code uint64, reason string) error

	SetDeadline(t time.Time) error
	SetWriteDeadline(t time.Time) error
}

type RecvStream interface {
	io.Reader
	io.Closer

	StreamID() uint64
	OpenInfo() []byte
	LocalAddr() net.Addr
	RemoteAddr() net.Addr

	Metadata() StreamMetadata

	CloseRead() error
	CancelRead(code uint64) error
	CloseWithError(code uint64, reason string) error

	SetDeadline(t time.Time) error
	SetReadDeadline(t time.Time) error
}

Native Interfaces

Native constructors return *zmux.Conn, which satisfies NativeSession.

NativeSession repeats the open/accept methods with native stream return types and adds native session controls:

type NativeSession interface {
	AcceptStream(ctx context.Context) (NativeStream, error)
	AcceptUniStream(ctx context.Context) (NativeRecvStream, error)

	OpenStream(ctx context.Context) (NativeStream, error)
	OpenUniStream(ctx context.Context) (NativeSendStream, error)

	OpenStreamWithOptions(ctx context.Context, opts OpenOptions) (NativeStream, error)
	OpenUniStreamWithOptions(ctx context.Context, opts OpenOptions) (NativeSendStream, error)

	OpenAndSend(ctx context.Context, p []byte) (NativeStream, int, error)
	OpenAndSendWithOptions(ctx context.Context, opts OpenOptions, p []byte) (NativeStream, int, error)

	OpenUniAndSend(ctx context.Context, p []byte) (NativeSendStream, int, error)
	OpenUniAndSendWithOptions(ctx context.Context, opts OpenOptions, p []byte) (NativeSendStream, int, error)

	Close() error
	CloseWithError(err error)
	Wait(ctx context.Context) error
	Closed() bool
	State() SessionState
	Stats() SessionStats

	Ping(ctx context.Context, echo []byte) (time.Duration, error)
	GoAway(lastAcceptedBidi, lastAcceptedUni uint64) error
	GoAwayWithError(lastAcceptedBidi, lastAcceptedUni, code uint64, reason string) error
	PeerGoAwayError() *ApplicationError
	PeerCloseError() *ApplicationError
	LocalPreface() Preface
	PeerPreface() Preface
	Negotiated() Negotiated
}

NativeStream, NativeSendStream, and NativeRecvStream extend the stable stream interfaces with native-only queries:

type NativeStream interface {
	Stream
	OpenedLocally() bool
	Bidirectional() bool
	ReadClosed() bool
	WriteClosed() bool
}

type NativeSendStream interface {
	SendStream
	OpenedLocally() bool
	Bidirectional() bool
	WriteClosed() bool
}

type NativeRecvStream interface {
	RecvStream
	OpenedLocally() bool
	Bidirectional() bool
	ReadClosed() bool
}

These interfaces are specific to native zmux. Adapters implement the stable surfaces.

Basic Usage

Open and use a bidirectional stream:

ctx := context.Background()

stream, err := session.OpenStream(ctx)
if err != nil {
	return err
}
defer stream.Close()

if _, err := stream.Write([]byte("ping")); err != nil {
	return err
}

buf := make([]byte, 4096)
n, err := stream.Read(buf)

Accept the peer side:

stream, err := session.AcceptStream(ctx)
if err != nil {
	return err
}
defer stream.Close()

Use unidirectional streams when only one side writes:

send, err := session.OpenUniStream(ctx)
if err != nil {
	return err
}
defer send.Close()

if _, err := send.Write([]byte("fire-and-forget")); err != nil {
	return err
}

recv, err := session.AcceptUniStream(ctx)
if err != nil {
	return err
}
defer recv.Close()

Open and send in one call:

stream, n, err := session.OpenAndSend(ctx, []byte("hello"))
send, n, err := session.OpenUniAndSend(ctx, []byte("hello"))

Use OpenAndSendWithOptions or OpenUniAndSendWithOptions when the opener also carries metadata.

Open Metadata

Use OpenOptions to send opener metadata:

priority := uint64(7)
group := uint64(2)

stream, err := session.OpenStreamWithOptions(ctx, zmux.OpenOptions{
	OpenInfo:        []byte("ssh"),
	InitialPriority: &priority,
	InitialGroup:    &group,
})

Read opener metadata from the receiving side:

info := stream.OpenInfo()
meta := stream.Metadata()

No extra capability setup is needed when both sides use nil config or DefaultConfig(). The session preface advertises supported metadata features and uses the intersection negotiated with the peer.

Update local metadata before the stream becomes peer-visible:

priority := uint64(9)
err := stream.UpdateMetadata(zmux.MetadataUpdate{
	Priority: &priority,
})

If metadata can no longer be represented on the wire, the call returns an error such as zmux.ErrPriorityUpdateUnavailable or zmux.ErrAdapterUnsupported.

Stream Close and Cancel

Stable stream methods mean:

  • WriteFinal / WritevFinal: write the final payload and finish the write side
  • CloseWrite: graceful write-side finish
  • CancelWrite(code): abort the local write side
  • CloseRead: stop the local read side with the default cancel code
  • CancelRead(code): stop the local read side with an explicit code
  • CloseWithError(code, reason): abort the whole stream
  • Close: local helper that closes both stream halves

Payload buffers passed to Write, WriteFinal, WritevFinal, OpenAndSend, OpenAndSendWithOptions, OpenUniAndSend, and OpenUniAndSendWithOptions are not retained after the call returns. Callers may reuse or mutate their input slices immediately after the method returns.

Examples:

if _, err := stream.WriteFinal([]byte("goodbye")); err != nil {
	return err
}

if err := stream.CloseRead(); err != nil {
	return err
}

if err := stream.CancelWrite(uint64(zmux.CodeCancelled)); err != nil {
	return err
}

if err := stream.CloseWithError(uint64(zmux.CodeInternal), "backend failed"); err != nil {
	return err
}

Native zmux treats whole-stream abort as a first-class operation, so CloseWithError exists on Stream, SendStream, and RecvStream.

Deadlines

Stream exposes the usual net.Conn deadlines:

_ = stream.SetDeadline(time.Now().Add(5 * time.Second))
_ = stream.SetReadDeadline(time.Now().Add(5 * time.Second))
_ = stream.SetWriteDeadline(time.Now().Add(5 * time.Second))

SendStream exposes write deadlines. RecvStream exposes read deadlines.

Session Lifecycle

Stable session methods mean:

  • Close(): graceful session close
  • CloseWithError(err): abortive session close
  • Wait(ctx): wait for termination
  • Closed(): report whether the session has terminated
  • State(): return the public session state
  • Stats(): return runtime counters and pressure snapshots
  • Stats().ActiveStreams: report active stream counts split by local/peer and bidi/uni

Example:

go func() {
	if err := session.Wait(context.Background()); err != nil {
		// reconnect / cleanup / report
	}
}()

Native Session Helpers

On native *zmux.Conn, you also have:

  • Ping(ctx, echo)
  • GoAway(lastAcceptedBidi, lastAcceptedUni)
  • GoAwayWithError(...)
  • PeerGoAwayError()
  • PeerCloseError()
  • LocalPreface()
  • PeerPreface()
  • Negotiated()

Example:

conn, err := zmux.New(rwc, cfg)
if err != nil {
	return err
}

if _, err := conn.Ping(ctx, []byte("probe")); err != nil {
	return err
}

Errors

Use standard Go error inspection:

if errors.Is(err, zmux.ErrSessionClosed) {
	// session is gone
}

var appErr *zmux.ApplicationError
if errors.As(err, &appErr) {
	// inspect appErr.Code / appErr.Reason
}

var structured *zmux.Error
if errors.As(err, &structured) {
	// inspect Scope / Operation / Source / Direction / TerminationKind
}

Common surface errors include:

  • zmux.ErrSessionClosed
  • zmux.ErrReadClosed
  • zmux.ErrWriteClosed
  • zmux.ErrOpenLimited
  • zmux.ErrOpenExpired
  • zmux.ErrPriorityUpdateUnavailable
  • zmux.ErrAdapterUnsupported

ApplicationError carries peer-visible application close codes and reason text.

A stream read returns io.EOF only after the peer's FIN and all of its data. When the session ends first, even through a NO_ERROR close, a read on a stream that did not get the peer's FIN (or whose unread data was discarded) fails with the session error, such as zmux.ErrSessionClosed.

Configuration

Pass *zmux.Config to tune capabilities, settings, keepalive, close timeouts, queue budgets, memory budgets, and event hooks:

cfg := zmux.DefaultConfig()
cfg.GracefulCloseDrainTimeout = 100 * time.Millisecond
cfg.PrefacePaddingMinBytes = 16
cfg.PrefacePaddingMaxBytes = 256
cfg.EventHandler = func(ev zmux.Event) {
	// observe stream/session lifecycle
}

session, err := zmux.New(rwc, cfg)

Start from DefaultConfig() for normal sessions. Constructors called with a nil config also use the process-wide default template. A literal &zmux.Config{} keeps the zero-value role (RoleInitiator), so set Role explicitly when endpoint ordering is not fixed.

Use ConfigureDefaultConfig during process initialization to adjust the default template:

zmux.ConfigureDefaultConfig(func(cfg *zmux.Config) {
	cfg.KeepaliveInterval = 30 * time.Second
	cfg.PingPaddingMaxBytes = 96
})

The template does not retain per-session random values such as TieBreakerNonce or Settings.PingPaddingKey; each session still generates fresh values when needed. Concurrent template updates are race-safe, but the last completed update wins. ResetDefaultConfig() restores the built-in template.

DefaultConfig() enables the standard metadata features, keepalive PINGs, and padding defaults. Open-time metadata is still sent only when an OpenOptions value asks for it. Set DisableCapabilities = true, KeepaliveInterval = 0, PrefacePadding = false, or PingPadding = false when a deployment needs those features disabled.

EstablishmentTimeout bounds the preface exchange (local preface write and peer preface read) on transports that support deadlines, such as net.Conn. Zero uses the 10s default and a negative value disables the bound. When the transport is a *tls.Conn that has not completed its handshake, the TLS handshake runs inside the preface I/O and shares this bound; call HandshakeContext first to bound it separately.

KeepaliveTimeout runs from when a keepalive PING is originated, so a peer whose transport stops draining (the PING cannot even be written) also fails the session with IDLE_TIMEOUT. Ping(ctx) returns ctx.Err() at its deadline on such a transport, and GracefulCloseDrainTimeout also bounds each GOAWAY write of a graceful Close.

When you need a self-contained config literal, set the non-zero defaults you depend on explicitly:

cfg := &zmux.Config{
	Role: zmux.RoleAuto,
	KeepaliveInterval:        30 * time.Second,
	KeepaliveMaxPingInterval: 2 * time.Minute,
	GracefulCloseDrainTimeout: 100 * time.Millisecond,
	EventHandler: func(ev zmux.Event) {
		// observe stream/session lifecycle
	},
}

session, err := zmux.New(rwc, cfg)

JoinConn

If a transport exposes separate read and write halves, combine them before constructing the session. Use JoinConn when those halves already satisfy zmux's directional ReadHalf and WriteHalf contracts:

joined := zmux.JoinConn(readHalf, writeHalf)
session, err := zmux.New(joined, nil)

Use the split I/O helpers when the transport only exposes ordinary io.Reader and io.Writer halves:

conn, err := zmux.ClientIO(reader, writer, cfg)
session, err := zmux.ClientIOSession(reader, writer, cfg)
joined := zmux.JoinIO(reader, writer)

JoinIO forwards deadlines and addresses when the underlying halves expose compatible methods, such as those on net.Conn. Plain io.Reader and io.Writer values that do not expose deadline methods report unsupported deadlines.

QUIC Adapter

The QUIC adapter lives in github.com/zmuxio/zmux-go/adapter/quicmux:

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

var qconn *quic.Conn
session := quicmux.WrapSession(qconn)

It implements the stable zmux.Session surface and maps the supported subset of metadata and termination semantics onto quic-go. See adapter/quicmux/README.md for adapter details.

Documentation

Overview

Package zmux implements the zmux v1 single-connection stream multiplexer.

It exposes Session and Stream interfaces for multiplexed streams over one transport connection.

Wire codecs, protocol-state helpers, and runtime policy stay in internal packages:

  • internal/wire
  • internal/state
  • internal/runtime

Treat internal packages as implementation details.

Index

Constants

View Source
const (
	Magic                   = wire.Magic
	PrefaceVersion          = wire.PrefaceVersion
	ProtoVersion            = wire.ProtoVersion
	MaxPrefaceSettingsBytes = wire.MaxPrefaceSettingsBytes
	MaxVarint62             = wire.MaxVarint62
)
View Source
const (
	RoleInitiator = wire.RoleInitiator
	RoleResponder = wire.RoleResponder
	RoleAuto      = wire.RoleAuto
)
View Source
const (
	SchedulerUnspecifiedOrBalanced = wire.SchedulerUnspecifiedOrBalanced
	SchedulerLatency               = wire.SchedulerLatency
	SchedulerBalancedFair          = wire.SchedulerBalancedFair
	SchedulerBulkThroughput        = wire.SchedulerBulkThroughput
	SchedulerGroupFair             = wire.SchedulerGroupFair
)
View Source
const (
	CapabilityOpenMetadata   = wire.CapabilityOpenMetadata
	CapabilityPriorityHints  = wire.CapabilityPriorityHints
	CapabilityStreamGroups   = wire.CapabilityStreamGroups
	CapabilityPriorityUpdate = wire.CapabilityPriorityUpdate
)
View Source
const (
	SettingInitialMaxStreamDataBidiLocallyOpened = wire.SettingInitialMaxStreamDataBidiLocallyOpened
	SettingInitialMaxStreamDataBidiPeerOpened    = wire.SettingInitialMaxStreamDataBidiPeerOpened
	SettingInitialMaxStreamDataUni               = wire.SettingInitialMaxStreamDataUni
	SettingInitialMaxData                        = wire.SettingInitialMaxData
	SettingMaxIncomingStreamsBidi                = wire.SettingMaxIncomingStreamsBidi
	SettingMaxIncomingStreamsUni                 = wire.SettingMaxIncomingStreamsUni
	SettingMaxFramePayload                       = wire.SettingMaxFramePayload
	SettingMaxControlPayloadBytes                = wire.SettingMaxControlPayloadBytes
	SettingMaxExtensionPayloadBytes              = wire.SettingMaxExtensionPayloadBytes
	SettingSchedulerHints                        = wire.SettingSchedulerHints
	SettingPingPaddingKey                        = wire.SettingPingPaddingKey
	SettingPrefacePadding                        = wire.SettingPrefacePadding
)
View Source
const (
	FrameTypeDATA        = wire.FrameTypeDATA
	FrameTypeMAXDATA     = wire.FrameTypeMAXDATA
	FrameTypeStopSending = wire.FrameTypeStopSending
	FrameTypePING        = wire.FrameTypePING
	FrameTypePONG        = wire.FrameTypePONG
	FrameTypeBLOCKED     = wire.FrameTypeBLOCKED
	FrameTypeRESET       = wire.FrameTypeRESET
	FrameTypeABORT       = wire.FrameTypeABORT
	FrameTypeGOAWAY      = wire.FrameTypeGOAWAY
	FrameTypeCLOSE       = wire.FrameTypeCLOSE
	FrameTypeEXT         = wire.FrameTypeEXT
)
View Source
const (
	FrameFlagOpenMetadata = wire.FrameFlagOpenMetadata
	FrameFlagFIN          = wire.FrameFlagFIN
)
View Source
const (
	MetadataStreamPriority = wire.MetadataStreamPriority
	MetadataStreamGroup    = wire.MetadataStreamGroup
	MetadataOpenInfo       = wire.MetadataOpenInfo
)
View Source
const (
	DIAGDebugText          = wire.DIAGDebugText
	DIAGRetryAfterMillis   = wire.DIAGRetryAfterMillis
	DIAGOffendingStreamID  = wire.DIAGOffendingStreamID
	DIAGOffendingFrameType = wire.DIAGOffendingFrameType
)
View Source
const (
	CodeNoError            = wire.CodeNoError
	CodeProtocol           = wire.CodeProtocol
	CodeFlowControl        = wire.CodeFlowControl
	CodeStreamLimit        = wire.CodeStreamLimit
	CodeRefusedStream      = wire.CodeRefusedStream
	CodeStreamState        = wire.CodeStreamState
	CodeStreamClosed       = wire.CodeStreamClosed
	CodeSessionClosing     = wire.CodeSessionClosing
	CodeCancelled          = wire.CodeCancelled
	CodeIdleTimeout        = wire.CodeIdleTimeout
	CodeFrameSize          = wire.CodeFrameSize
	CodeUnsupportedVersion = wire.CodeUnsupportedVersion
	CodeRoleConflict       = wire.CodeRoleConflict
	CodeInternal           = wire.CodeInternal
)
View Source
const (
	EXTPriorityUpdate = wire.EXTPriorityUpdate
)

Variables

View Source
var (
	ErrNilConn                   = errors.New("zmux: nil conn")
	ErrSessionClosed             = errors.New("zmux: session closed")
	ErrReadClosed                = errors.New("zmux: read side closed")
	ErrWriteClosed               = errors.New("zmux: write side closed")
	ErrStreamNotReadable         = errors.New("zmux: stream is not readable")
	ErrStreamNotWritable         = errors.New("zmux: stream is not writable")
	ErrOpenInfoUnavailable       = wire.ErrOpenInfoUnavailable
	ErrOpenMetadataTooLarge      = wire.ErrOpenMetadataTooLarge
	ErrOpenLimited               = errors.New("zmux: too many provisional local opens")
	ErrOpenExpired               = errors.New("zmux: provisional local open expired before first-frame commit")
	ErrAdapterUnsupported        = errors.New("zmux: feature not supported by adapter")
	ErrPriorityUpdateUnavailable = errors.New("zmux: metadata update requires negotiated priority_update and matching semantic capability")
	ErrPriorityUpdateTooLarge    = errors.New("zmux: priority update exceeds peer max_extension_payload_bytes")
	ErrGracefulCloseTimeout      = errors.New("zmux: graceful close drain timed out")
	ErrEmptyMetadataUpdate       = errors.New("zmux: metadata update has no fields")
	ErrKeepaliveTimeout          = errors.New("zmux: keepalive timeout")
)

Functions

func AppendTLV

func AppendTLV(dst []byte, typ uint64, value []byte) ([]byte, error)

func AppendVarint

func AppendVarint(dst []byte, v uint64) ([]byte, error)

func ConfigureDefaultConfig added in v1.1.0

func ConfigureDefaultConfig(fn func(*Config))

ConfigureDefaultConfig mutates the process-wide default configuration template used by DefaultConfig and by constructors called with nil Config.

Call it during process initialization before creating sessions. Existing sessions are not affected. Concurrent calls are race-safe; last write wins.

Per-session random fields are not retained in the template: TieBreakerNonce and Settings.PingPaddingKey are cleared after fn returns so each session can generate fresh values.

func EncodeVarint

func EncodeVarint(v uint64) ([]byte, error)

func IsErrorCode

func IsErrorCode(err error, code ErrorCode) bool

IsErrorCode reports whether err carries the given wire or application code.

func ParseVarint

func ParseVarint(src []byte) (uint64, int, error)

func ReadVarint

func ReadVarint(r io.ByteReader) (uint64, int, error)

func ReferenceProfileClaimGate

func ReferenceProfileClaimGate() []string

ReferenceProfileClaimGate returns the repository-defined reference-profile gate conditions from the current zmux document set. The returned slice is a copy and may be modified by the caller.

func ResetDefaultConfig added in v1.1.0

func ResetDefaultConfig()

ResetDefaultConfig restores the built-in process-wide default configuration template.

func VarintLen

func VarintLen(v uint64) (int, error)

Types

type AcceptBacklogStats

type AcceptBacklogStats struct {
	Count      int
	CountLimit int
	AtCountCap bool
	Bytes      uint64
	BytesLimit uint64
	AtBytesCap bool
	Refused    uint64
}

AcceptBacklogStats reports accepted-stream backlog usage.

type ActiveStreamStats added in v1.0.9

type ActiveStreamStats struct {
	// LocalBidi counts active bidirectional streams opened by this endpoint.
	LocalBidi uint64
	// LocalUni counts active send-only streams opened by this endpoint.
	LocalUni uint64
	// PeerBidi counts active bidirectional streams opened by the peer.
	PeerBidi uint64
	// PeerUni counts active receive-only streams opened by the peer.
	PeerUni uint64
	// Total is the saturating sum of all active stream counters.
	Total uint64
}

ActiveStreamStats reports active stream slots by opener and direction.

type ApplicationError

type ApplicationError struct {
	Code   uint64
	Reason string
}

ApplicationError carries an application code and optional reason text.

func (*ApplicationError) ApplicationCode

func (e *ApplicationError) ApplicationCode() uint64

func (*ApplicationError) Error

func (e *ApplicationError) Error() string

func (*ApplicationError) Is

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

type Capabilities

type Capabilities = wire.Capabilities

type Claim

type Claim string

Claim identifies one repository-defined standardized claim string from the zmux document set.

const (
	ClaimWireV1                 Claim = "zmux-wire-v1"
	ClaimAPISemanticsProfileV1  Claim = "zmux-api-semantics-profile-v1"
	ClaimStreamAdapterProfileV1 Claim = "zmux-stream-adapter-profile-v1"
	ClaimOpenMetadata           Claim = "zmux-open_metadata"
	ClaimPriorityUpdate         Claim = "zmux-priority_update"
)

func CoreModuleTargetClaims added in v1.1.0

func CoreModuleTargetClaims() []Claim

CoreModuleTargetClaims returns the repository-defined conformance claims targeted by the core zmux module. The returned slice is a copy and may be modified by the caller.

func KnownClaims

func KnownClaims() []Claim

KnownClaims returns the repository-defined claim names recognized by this package. The returned slice is a copy and may be modified by the caller.

func (Claim) AcceptanceChecklist

func (c Claim) AcceptanceChecklist() []string

AcceptanceChecklist returns the repository-defined minimum acceptance checklist for the claim. The returned slice is a copy and may be modified by the caller.

func (Claim) RequiredConformanceSuites

func (c Claim) RequiredConformanceSuites() []ConformanceSuite

RequiredConformanceSuites returns the repository-defined local suite selection buckets needed to substantiate the claim.

func (Claim) Valid

func (c Claim) Valid() bool

Valid reports whether the claim matches one of the repository-defined claim names in the current zmux document set.

type Config

type Config struct {
	Role            Role
	TieBreakerNonce uint64
	MinProto        uint64
	MaxProto        uint64
	// Capabilities advertises optional protocol features.
	// Zero uses the default capability set.
	Capabilities Capabilities
	// DisableCapabilities advertises no optional protocol features.
	DisableCapabilities bool
	Settings            Settings
	NonceSource         io.Reader
	// PrefacePadding adds one ignored settings TLV to the local preface.
	PrefacePadding bool
	// PrefacePaddingMinBytes is the lower padding length bound. Zero uses the default.
	PrefacePaddingMinBytes uint64
	// PrefacePaddingMaxBytes is the upper padding length bound. Zero uses the default.
	PrefacePaddingMaxBytes uint64
	// EstablishmentTimeout bounds session establishment: the local preface
	// write and the peer preface read. It is enforced through the transport's
	// read/write deadlines (net.Conn); for an un-handshaken tls.Conn the TLS
	// handshake runs inside those reads and writes and shares the bound.
	// Zero uses the default (10s). A negative value disables the bound.
	EstablishmentTimeout time.Duration
	// KeepaliveInterval bounds idle time before an automatic PING.
	// Zero disables automatic keepalive.
	KeepaliveInterval time.Duration
	// KeepaliveMaxPingInterval bounds time between local PINGs while keepalive is enabled.
	// Zero disables this extra cap.
	KeepaliveMaxPingInterval time.Duration
	// KeepaliveTimeout bounds how long a keepalive PING may remain unanswered.
	// It runs from when the PING is originated, so a transport that stops
	// draining, and never even writes the PING, also trips it.
	// Zero uses an adaptive default.
	KeepaliveTimeout time.Duration
	// PingPadding pads local PINGs and recognized PONG replies.
	// It also advertises a per-session PingPaddingKey.
	PingPadding bool
	// PingPaddingMinBytes is the lower PING/PONG padding bound.
	// For PING, it includes the fixed 8-byte tag. Zero uses the default.
	PingPaddingMinBytes uint64
	// PingPaddingMaxBytes is the upper PING/PONG padding bound.
	// For PING, it includes the fixed 8-byte tag. Zero uses the default.
	PingPaddingMaxBytes uint64

	// SessionMemoryCap overrides the tracked-session-memory cap. Zero uses the default.
	SessionMemoryCap uint64
	// PerStreamQueuedDataHWM overrides the per-stream queued-data high watermark.
	// Zero uses the default.
	PerStreamQueuedDataHWM uint64
	// SessionQueuedDataHWM overrides the session-wide queued-data high watermark.
	// Zero uses the default.
	SessionQueuedDataHWM uint64
	// UrgentQueuedBytesCap overrides the urgent/control lane cap. Zero uses the default.
	UrgentQueuedBytesCap uint64
	// PendingControlBytesBudget overrides the coalesced control byte budget.
	// Zero uses the default.
	PendingControlBytesBudget uint64
	// PendingPriorityBytesBudget overrides the coalesced advisory byte budget.
	// Zero uses the default.
	PendingPriorityBytesBudget uint64
	// RetainedOpenInfoBytesBudget overrides the retained open_info byte budget.
	// Zero uses the default.
	RetainedOpenInfoBytesBudget uint64
	// RetainedPeerReasonBytesBudget overrides the retained peer reason-text byte budget.
	// Zero uses the default.
	RetainedPeerReasonBytesBudget uint64
	// AggregateLateDataCap overrides the aggregate late-data allowance reported
	// by Stats (PressureStats.AggregateLateDataAtCap). The aggregate counts late
	// bytes still retained by stopped or aborted streams and their tombstones.
	// Exceeding it never fails the session; further late tail is discarded and
	// its session credit released. Zero uses the default.
	AggregateLateDataCap uint64
	// AcceptBacklogLimit overrides the visible accept backlog count. Zero uses the default.
	AcceptBacklogLimit int
	// AcceptBacklogBytesLimit overrides visible accept backlog bytes. Zero uses the default.
	AcceptBacklogBytesLimit uint64
	// TombstoneLimit overrides the retained tombstone count. Zero uses the default.
	TombstoneLimit int
	// MarkerOnlyUsedStreamLimit overrides retained marker-only used-stream
	// entries, up to the default derived from the session memory cap. Past the
	// limit the oldest markers are coarsened; the session never fails for it.
	// Zero uses the derived default.
	MarkerOnlyUsedStreamLimit int
	// AbuseWindow overrides the local anti-abuse accounting window. Zero uses the default.
	AbuseWindow time.Duration
	// HiddenAbortChurnWindow overrides hidden abort churn detection. Zero uses the default.
	HiddenAbortChurnWindow time.Duration
	// HiddenAbortChurnThreshold overrides hidden open-then-abort churn. Zero uses the default.
	HiddenAbortChurnThreshold uint32
	// VisibleTerminalChurnWindow overrides visible terminal churn detection.
	// Zero uses the default.
	VisibleTerminalChurnWindow time.Duration
	// VisibleTerminalChurnThreshold overrides visible open-then-reset/abort churn.
	// Zero uses the default.
	VisibleTerminalChurnThreshold uint32
	// InboundControlFrameBudget overrides the inbound control-frame window.
	// Zero uses the default.
	InboundControlFrameBudget uint32
	// InboundControlBytesBudget overrides the inbound control-byte window.
	// Zero uses the default.
	InboundControlBytesBudget uint64
	// InboundExtFrameBudget overrides the inbound EXT-frame window. Zero uses the default.
	InboundExtFrameBudget uint32
	// InboundExtBytesBudget overrides the inbound EXT-byte window. Zero uses the default.
	InboundExtBytesBudget uint64
	// InboundMixedFrameBudget overrides the mixed control/EXT frame window.
	// Zero uses the default.
	InboundMixedFrameBudget uint32
	// InboundMixedBytesBudget overrides the mixed control/EXT byte window.
	// Zero uses the default.
	InboundMixedBytesBudget uint64
	// NoOpControlFloodThreshold overrides the mixed no-op control threshold.
	// Zero uses the default.
	NoOpControlFloodThreshold uint32
	// NoOpMaxDataFloodThreshold overrides the no-op MAX_DATA threshold.
	// Zero uses the default.
	NoOpMaxDataFloodThreshold uint32
	// NoOpBlockedFloodThreshold overrides the no-op BLOCKED threshold. Zero uses the default.
	NoOpBlockedFloodThreshold uint32
	// NoOpZeroDataFloodThreshold overrides the zero-length DATA threshold.
	// Zero uses the default.
	NoOpZeroDataFloodThreshold uint32
	// NoOpPriorityUpdateFloodThreshold overrides the no-op PRIORITY_UPDATE threshold.
	// Zero uses the default.
	NoOpPriorityUpdateFloodThreshold uint32
	// GroupRebucketChurnThreshold overrides repeated stream_group rebucketing.
	// Zero uses the default.
	GroupRebucketChurnThreshold uint32
	// InboundPingFloodThreshold overrides the inbound PING flood threshold.
	// Zero uses the default.
	InboundPingFloodThreshold uint32
	// StopSendingGracefulDrainWindow bounds graceful drain after peer STOP_SENDING.
	// Zero uses the default.
	StopSendingGracefulDrainWindow time.Duration
	// StopSendingGracefulTailCap bounds DATA|FIN tail after peer STOP_SENDING.
	// Zero uses the default.
	StopSendingGracefulTailCap uint64
	// GracefulCloseDrainTimeout bounds Close waiting for graceful drain. It
	// also bounds each wait for a GOAWAY write, so Close cannot hang on a
	// transport that stopped draining. Zero uses the default.
	GracefulCloseDrainTimeout time.Duration

	// EventHandler receives lightweight connection/stream lifecycle notifications.
	EventHandler EventHandler
}

Config controls session establishment and runtime behavior.

Prefer starting from DefaultConfig(). Constructors also fill zero capability, protocol, setting, and nonce-source fields with defaults.

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns a copy of the process-wide default configuration template.

func (Config) LocalPreface

func (c Config) LocalPreface() (Preface, error)

type ConformanceSuite

type ConformanceSuite string

ConformanceSuite identifies one repository-defined local conformance suite selection bucket derived from CONFORMANCE.md.

const (
	SuiteCoreWireInteroperability     ConformanceSuite = "core-wire-interoperability"
	SuiteInvalidInputHandling         ConformanceSuite = "invalid-input-handling"
	SuiteExtensionTolerance           ConformanceSuite = "extension-tolerance"
	SuiteCoreStreamLifecycle          ConformanceSuite = "core-stream-lifecycle"
	SuiteCoreFlowControl              ConformanceSuite = "core-flow-control"
	SuiteCoreSessionLifecycle         ConformanceSuite = "core-session-lifecycle"
	SuiteOpenMetadata                 ConformanceSuite = "open_metadata"
	SuitePriorityUpdate               ConformanceSuite = "priority_update"
	SuitePriorityHintsAndStreamGroups ConformanceSuite = "priority-hints-and-stream-groups"
	SuiteV1ProfileCompatibility       ConformanceSuite = "v1-profile-compatibility"
	SuiteAPISemanticsProfile          ConformanceSuite = "api-semantics-profile"
	SuiteStreamAdapterProfile         ConformanceSuite = "stream-adapter-profile"
	SuiteReferenceProfileClaimGate    ConformanceSuite = "reference-profile-claim-gate"
	SuiteReferenceQualityBehaviors    ConformanceSuite = "reference-quality-behaviors"
)

func CoreModuleTargetSuites added in v1.1.0

func CoreModuleTargetSuites() []ConformanceSuite

CoreModuleTargetSuites returns the ordered union of conformance suites needed to substantiate the core zmux module's target claims and profiles. The returned slice is a copy and may be modified by the caller.

func KnownConformanceSuites

func KnownConformanceSuites() []ConformanceSuite

KnownConformanceSuites returns the repository-defined local conformance suite selection buckets recognized by this package.

func (ConformanceSuite) Valid

func (s ConformanceSuite) Valid() bool

Valid reports whether the suite matches one of the repository-defined local conformance suite selection buckets.

type Conn

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

Conn is the native zmux session implementation.

func Client

func Client(conn io.ReadWriteCloser, cfg *Config) (*Conn, error)

Client establishes a native initiator session.

func ClientIO added in v1.1.2

func ClientIO(reader io.Reader, writer io.Writer, cfg *Config) (*Conn, error)

ClientIO establishes a native initiator session on separate reader and writer halves.

func New

func New(conn io.ReadWriteCloser, cfg *Config) (*Conn, error)

New establishes a native zmux session.

func NewIO added in v1.1.2

func NewIO(reader io.Reader, writer io.Writer, cfg *Config) (*Conn, error)

NewIO establishes a native zmux session on separate reader and writer halves.

func Server

func Server(conn io.ReadWriteCloser, cfg *Config) (*Conn, error)

Server establishes a native responder session.

func ServerIO added in v1.1.2

func ServerIO(reader io.Reader, writer io.Writer, cfg *Config) (*Conn, error)

ServerIO establishes a native responder session on separate reader and writer halves.

func (*Conn) AcceptStream

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

func (*Conn) AcceptUniStream

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

func (*Conn) Close

func (c *Conn) Close() error

func (*Conn) CloseWithError added in v1.0.4

func (c *Conn) CloseWithError(err error)

func (*Conn) Closed

func (c *Conn) Closed() bool

Closed reports whether the session has terminated.

func (*Conn) GoAway

func (c *Conn) GoAway(lastAcceptedBidi, lastAcceptedUni uint64) error

func (*Conn) GoAwayWithError

func (c *Conn) GoAwayWithError(lastAcceptedBidi, lastAcceptedUni, code uint64, reason string) error

func (*Conn) LocalPreface

func (c *Conn) LocalPreface() Preface

func (*Conn) Negotiated

func (c *Conn) Negotiated() Negotiated

func (*Conn) OpenAndSend

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

func (*Conn) OpenAndSendWithOptions

func (c *Conn) OpenAndSendWithOptions(ctx context.Context, opts OpenOptions, p []byte) (NativeStream, int, error)

func (*Conn) OpenStream

func (c *Conn) OpenStream(ctx context.Context) (NativeStream, error)

func (*Conn) OpenStreamWithOptions

func (c *Conn) OpenStreamWithOptions(ctx context.Context, opts OpenOptions) (NativeStream, error)

func (*Conn) OpenUniAndSend

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

func (*Conn) OpenUniAndSendWithOptions

func (c *Conn) OpenUniAndSendWithOptions(ctx context.Context, opts OpenOptions, p []byte) (NativeSendStream, int, error)

func (*Conn) OpenUniStream

func (c *Conn) OpenUniStream(ctx context.Context) (NativeSendStream, error)

func (*Conn) OpenUniStreamWithOptions

func (c *Conn) OpenUniStreamWithOptions(ctx context.Context, opts OpenOptions) (NativeSendStream, error)

func (*Conn) PeerCloseError

func (c *Conn) PeerCloseError() *ApplicationError

PeerCloseError returns the last peer CLOSE error, if any.

func (*Conn) PeerGoAwayError

func (c *Conn) PeerGoAwayError() *ApplicationError

PeerGoAwayError returns the last peer GOAWAY error, if any.

func (*Conn) PeerPreface

func (c *Conn) PeerPreface() Preface

func (*Conn) Ping

func (c *Conn) Ping(ctx context.Context, echo []byte) (time.Duration, error)

func (*Conn) State

func (c *Conn) State() SessionState

State returns the current public session state.

func (*Conn) Stats

func (c *Conn) Stats() SessionStats

func (*Conn) Wait

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

type DIAGType

type DIAGType = wire.DIAGType

type DiagnosticStats

type DiagnosticStats struct {
	DroppedPriorityUpdates      uint64
	DroppedLocalPriorityUpdates uint64
	LateDataAfterCloseRead      uint64
	LateDataAfterReset          uint64
	LateDataAfterAbort          uint64
	CoalescedTerminal           uint64
	SupersededTerminal          uint64
	SkippedCloseOnDeadIO        uint64
	CloseFrameAdmissionTimeouts uint64
	CloseFrameFlushTimeouts     uint64
	CloseFrameFlushErrors       uint64
	ProtocolBacklogBlocked      uint64
	MarkerOnlyRangeCount        int
}

DiagnosticStats reports ingress, drop, and late-data counters.

type Direction

type Direction uint8

Direction identifies which stream direction the error applies to.

const (
	DirectionUnknown Direction = iota
	DirectionRead
	DirectionWrite
	DirectionBoth
)

func (Direction) String

func (d Direction) String() string

type DuplexByteStream

type DuplexByteStream interface {
	io.Reader
	io.Writer
	io.Closer
}

DuplexByteStream is the minimal transport shape accepted by session constructors.

type EXTSubtype

type EXTSubtype = wire.EXTSubtype

type Error

type Error struct {
	Scope           Scope
	Operation       Operation
	Source          Source
	WireCode        uint64
	ReasonText      string
	Direction       Direction
	TerminationKind TerminationKind
	Err             error
}

Error is the structured error wrapper returned by public APIs.

func AsStructuredError

func AsStructuredError(err error) (*Error, bool)

AsStructuredError returns the structured error wrapper when present.

func (*Error) Error

func (e *Error) Error() string

func (*Error) Unwrap

func (e *Error) Unwrap() error

type ErrorCode

type ErrorCode = wire.ErrorCode

func ErrorCodeOf

func ErrorCodeOf(err error) (ErrorCode, bool)

ErrorCodeOf returns the wire or application error code when one is present.

type Event

type Event struct {
	Type               EventType
	SessionState       SessionState
	StreamID           uint64
	Stream             Stream
	Local              bool
	Bidi               bool
	Time               time.Time
	Err                error
	ApplicationVisible bool
}

Event is delivered to EventHandler.

type EventHandler

type EventHandler func(Event)

EventHandler receives opt-in stream and session events.

type EventType

type EventType int

EventType identifies an event kind.

const (
	// EventStreamOpened is emitted when a local stream becomes peer-visible.
	EventStreamOpened EventType = iota + 1
	// EventStreamAccepted is emitted when a peer-opened stream is accepted.
	EventStreamAccepted
	// EventSessionClosed is emitted when the session terminates.
	EventSessionClosed
)

type FlushStats

type FlushStats struct {
	Count      uint64
	LastAt     time.Time
	LastFrames int
	LastBytes  int
}

FlushStats reports the most recent writer flush.

type Frame

type Frame = wire.Frame

func ParseFrame

func ParseFrame(src []byte, limits Limits) (Frame, int, error)

func ReadFrame

func ReadFrame(r io.Reader, limits Limits) (Frame, error)

type FrameType

type FrameType = wire.FrameType

type HiddenStats

type HiddenStats struct {
	Refused              uint64
	Reaped               uint64
	UnreadBytesDiscarded uint64
	Retained             int
	SoftCap              int
	HardCap              int
	AtSoftCap            bool
	AtHardCap            bool
}

HiddenStats reports hidden-stream counters and limits.

type ImplementationProfile

type ImplementationProfile string

ImplementationProfile identifies one repository-defined implementation profile name from the zmux document set.

const (
	ProfileV1          ImplementationProfile = "zmux-v1"
	ProfileReferenceV1 ImplementationProfile = "zmux-reference-profile-v1"
)

func CoreModuleTargetImplementationProfiles added in v1.1.0

func CoreModuleTargetImplementationProfiles() []ImplementationProfile

CoreModuleTargetImplementationProfiles returns the repository-defined implementation profiles targeted by the core zmux module. The returned slice is a copy and may be modified by the caller.

func KnownImplementationProfiles

func KnownImplementationProfiles() []ImplementationProfile

KnownImplementationProfiles returns the repository-defined implementation profile names recognized by this package. The returned slice is a copy and may be modified by the caller.

func (ImplementationProfile) AcceptanceChecklist

func (p ImplementationProfile) AcceptanceChecklist() []string

AcceptanceChecklist returns the repository-defined minimum acceptance checklist for the implementation profile. The returned slice is a copy and may be modified by the caller.

func (ImplementationProfile) Claims

func (p ImplementationProfile) Claims() []Claim

Claims returns the repository-defined claim bundle associated with the given implementation profile. The returned slice is a copy and may be modified by the caller.

func (ImplementationProfile) ReleaseCertificationGate

func (p ImplementationProfile) ReleaseCertificationGate() []ConformanceSuite

ReleaseCertificationGate returns the repository-defined pass/fail local suite selection gate for the implementation profile.

func (ImplementationProfile) RequiredConformanceSuites

func (p ImplementationProfile) RequiredConformanceSuites() []ConformanceSuite

RequiredConformanceSuites returns the repository-defined local suite selection buckets needed to substantiate the implementation profile.

func (ImplementationProfile) Valid

func (p ImplementationProfile) Valid() bool

Valid reports whether the implementation profile matches one of the repository-defined implementation-profile names in the current zmux document set.

type JoinedConn

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

JoinedConn adapts independent read and write halves into a net.Conn.

Either half may be nil. PauseRead and PauseWrite detach ownership until the returned handle resumes the half.

func JoinConn

func JoinConn(read ReadHalf, write WriteHalf) *JoinedConn

JoinConn adapts one read half plus one write half into a net.Conn-compatible wrapper. Either half may be nil.

func JoinIO added in v1.1.2

func JoinIO(reader io.Reader, writer io.Writer) *JoinedConn

JoinIO adapts ordinary Go I/O halves into a net.Conn-compatible JoinedConn.

Either half may be nil, matching JoinConn. The returned connection forwards deadline and address calls when the underlying half exposes compatible methods such as SetReadDeadline, SetWriteDeadline, LocalAddr, or RemoteAddr. Plain io.Reader/io.Writer values that do not expose deadline methods return errors.ErrUnsupported from deadline setters.

func (*JoinedConn) Close

func (c *JoinedConn) Close() error

Close closes the currently attached halves and wakes all blocked operations. Halves that were already detached through PauseRead or PauseWrite remain caller-owned and are not closed by JoinedConn.

func (*JoinedConn) CloseRead

func (c *JoinedConn) CloseRead() error

CloseRead closes the currently attached read half. If no read half is attached, CloseRead is a no-op.

func (*JoinedConn) CloseWrite

func (c *JoinedConn) CloseWrite() error

CloseWrite closes the currently attached write half. If no write half is attached, CloseWrite is a no-op.

func (*JoinedConn) LocalAddr

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

func (*JoinedConn) PauseRead

func (c *JoinedConn) PauseRead(ctx context.Context) (*PausedReadHalf, error)

PauseRead waits for the read side to become quiescent, detaches the current read half, and returns a handle that owns it. The returned handle may stage a replacement half before Resume reattaches it.

func (*JoinedConn) PauseWrite

func (c *JoinedConn) PauseWrite(ctx context.Context) (*PausedWriteHalf, error)

PauseWrite waits for the write side to become quiescent, detaches the current write half, and returns a handle that owns it. The returned handle may stage a replacement half before Resume reattaches it.

func (*JoinedConn) Read

func (c *JoinedConn) Read(p []byte) (int, error)

func (*JoinedConn) ReadHalf

func (c *JoinedConn) ReadHalf() ReadHalf

ReadHalf returns the currently attached read half. It returns nil while the read side is paused, detached, or absent.

func (*JoinedConn) RemoteAddr

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

func (*JoinedConn) SetDeadline

func (c *JoinedConn) SetDeadline(t time.Time) error

func (*JoinedConn) SetReadDeadline

func (c *JoinedConn) SetReadDeadline(t time.Time) error

func (*JoinedConn) SetWriteDeadline

func (c *JoinedConn) SetWriteDeadline(t time.Time) error

func (*JoinedConn) Write

func (c *JoinedConn) Write(p []byte) (int, error)

func (*JoinedConn) WriteHalf

func (c *JoinedConn) WriteHalf() WriteHalf

WriteHalf returns the currently attached write half. It returns nil while the write side is paused, detached, or absent.

type Limits

type Limits = wire.Limits

type MetadataUpdate

type MetadataUpdate struct {
	Priority *uint64
	Group    *uint64
}

MetadataUpdate carries post-open advisory metadata changes.

type NativeRecvStream

type NativeRecvStream interface {
	RecvStream
	OpenedLocally() bool
	Bidirectional() bool
	ReadClosed() bool
}

NativeRecvStream is the native receive-only stream interface.

type NativeSendStream

type NativeSendStream interface {
	SendStream
	OpenedLocally() bool
	Bidirectional() bool
	WriteClosed() bool
}

NativeSendStream is the native send-only stream interface.

type NativeSession added in v1.0.4

type NativeSession interface {
	AcceptStream(ctx context.Context) (NativeStream, error)
	AcceptUniStream(ctx context.Context) (NativeRecvStream, error)
	OpenStream(ctx context.Context) (NativeStream, error)
	OpenUniStream(ctx context.Context) (NativeSendStream, error)
	OpenStreamWithOptions(ctx context.Context, opts OpenOptions) (NativeStream, error)
	OpenUniStreamWithOptions(ctx context.Context, opts OpenOptions) (NativeSendStream, error)
	OpenAndSend(ctx context.Context, p []byte) (NativeStream, int, error)
	OpenAndSendWithOptions(ctx context.Context, opts OpenOptions, p []byte) (NativeStream, int, error)
	OpenUniAndSend(ctx context.Context, p []byte) (NativeSendStream, int, error)
	OpenUniAndSendWithOptions(ctx context.Context, opts OpenOptions, p []byte) (NativeSendStream, int, error)
	Close() error
	CloseWithError(err error)
	Wait(ctx context.Context) error
	Closed() bool
	State() SessionState
	Stats() SessionStats
	Ping(ctx context.Context, echo []byte) (time.Duration, error)
	GoAway(lastAcceptedBidi, lastAcceptedUni uint64) error
	GoAwayWithError(lastAcceptedBidi, lastAcceptedUni, code uint64, reason string) error
	PeerGoAwayError() *ApplicationError
	PeerCloseError() *ApplicationError
	LocalPreface() Preface
	PeerPreface() Preface
	Negotiated() Negotiated
}

NativeSession is the native zmux session interface.

It repeats open and accept methods with native stream return types because Go does not support covariant interface return types.

type NativeStream

type NativeStream interface {
	Stream
	OpenedLocally() bool
	Bidirectional() bool
	ReadClosed() bool
	WriteClosed() bool
}

NativeStream is the native bidirectional stream interface.

type Negotiated

type Negotiated = wire.Negotiated

func NegotiatePrefaces

func NegotiatePrefaces(local, peer Preface) (Negotiated, error)

type OpenOptions

type OpenOptions struct {
	InitialPriority *uint64
	InitialGroup    *uint64
	OpenInfo        []byte
}

OpenOptions carries optional open-time inputs for a new stream.

InitialPriority and InitialGroup may remain local sender-policy hints when the corresponding peer-visible carriage is unavailable. OpenInfo is peer-visible open-time metadata and is rejected if it cannot be carried on the opening frame.

type Operation

type Operation uint8

Operation identifies the API operation that failed.

const (
	OperationUnknown Operation = iota
	OperationOpen
	OperationAccept
	OperationRead
	OperationWrite
	OperationClose
)

func (Operation) String

func (o Operation) String() string

type PausedReadHalf

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

PausedReadHalf owns a detached read half until Resume reattaches it.

func (*PausedReadHalf) Current

func (p *PausedReadHalf) Current() ReadHalf

Current returns the read half currently owned by the pause handle.

func (*PausedReadHalf) Resume

func (p *PausedReadHalf) Resume() error

Resume reattaches the staged read half and re-enables upper-layer reads.

func (*PausedReadHalf) Set

func (p *PausedReadHalf) Set(next ReadHalf) ReadHalf

Set stages next as the read half to attach on Resume and returns the previously staged half. Passing nil detaches the read side.

type PausedWriteHalf

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

PausedWriteHalf owns a detached write half until Resume reattaches it.

func (*PausedWriteHalf) Current

func (p *PausedWriteHalf) Current() WriteHalf

Current returns the write half currently owned by the pause handle.

func (*PausedWriteHalf) Resume

func (p *PausedWriteHalf) Resume() error

Resume reattaches the staged write half and re-enables upper-layer writes.

func (*PausedWriteHalf) Set

func (p *PausedWriteHalf) Set(next WriteHalf) WriteHalf

Set stages next as the write half to attach on Resume and returns the previously staged half. Passing nil detaches the write side.

type Preface

type Preface = wire.Preface

func ParsePreface

func ParsePreface(data []byte) (Preface, error)

func ReadPreface

func ReadPreface(r io.Reader) (Preface, error)

type PressureStats

type PressureStats struct {
	ReceiveBacklog         uint64
	ReceiveBacklogHigh     bool
	AggregateLateData      uint64
	AggregateLateDataAtCap bool
	RetainedState          uint64
	RetainedBuckets        RetainedStateBreakdown
	RetainedOpenInfo       uint64
	RetainedPeerReasons    uint64
	OutstandingPingBytes   uint64
	TrackedBuffered        uint64
	TrackedBufferedLimit   uint64
	TrackedBufferedHigh    bool
	TrackedBufferedAtCap   bool
	OrdinaryQueued         uint64
	AdvisoryQueued         uint64
	UrgentQueued           uint64
	PendingControl         uint64
	PendingAdvisory        uint64
	PreparedAdvisory       uint64
	PendingTerminal        uint64
	PendingTerminalCount   int
	PendingProtocolJobs    int
}

PressureStats reports queue, memory, and retention pressure.

type ProgressStats

type ProgressStats struct {
	TransportProgressAt   time.Time
	MuxControlProgressAt  time.Time
	StreamProgressAt      time.Time
	ApplicationProgressAt time.Time
}

ProgressStats reports recent transport, mux, stream, and app activity times.

type ProvisionalStats

type ProvisionalStats struct {
	Bidi       int
	Uni        int
	SoftCap    int
	HardCap    int
	BidiAtSoft bool
	UniAtSoft  bool
	BidiAtHard bool
	UniAtHard  bool
	Limited    uint64
	Expired    uint64
}

ProvisionalStats reports provisional-open counts and limits.

type QueueStats

type QueueStats struct {
	Urgent   int
	Advisory int
	Ordinary int
	Total    int
}

QueueStats reports writer queue depths.

type ReadHalf

type ReadHalf interface {
	io.Reader
	CloseRead() error
	SetReadDeadline(time.Time) error
	LocalAddr() net.Addr
	RemoteAddr() net.Addr
}

ReadHalf is the minimal directional read-side contract required by JoinedConn.

type ReasonStats

type ReasonStats struct {
	Reset         map[uint64]uint64
	ResetOverflow uint64
	Abort         map[uint64]uint64
	AbortOverflow uint64
}

ReasonStats counts observed reset and abort codes. Overflow counters count events folded after the distinct-code map cap is reached.

type RecvStream

type RecvStream interface {
	io.Reader
	io.Closer
	StreamID() uint64
	OpenInfo() []byte
	LocalAddr() net.Addr
	RemoteAddr() net.Addr
	Metadata() StreamMetadata
	CloseRead() error
	CancelRead(code uint64) error
	CloseWithError(code uint64, reason string) error
	SetDeadline(t time.Time) error
	SetReadDeadline(t time.Time) error
}

RecvStream is the stable receive-only stream interface.

type RetainedBucketStats

type RetainedBucketStats struct {
	Count int
	Bytes uint64
}

RetainedBucketStats reports retained item and byte counts.

type RetainedStateBreakdown

type RetainedStateBreakdown struct {
	HiddenControl    RetainedBucketStats
	AcceptBacklog    RetainedBucketStats
	Provisionals     RetainedBucketStats
	VisibleTombstone RetainedBucketStats
	MarkerOnly       RetainedBucketStats
}

RetainedStateBreakdown reports retained bytes by category.

func (RetainedStateBreakdown) TotalBytes

func (r RetainedStateBreakdown) TotalBytes() uint64

type Role

type Role = wire.Role

type SchedulerHint

type SchedulerHint = wire.SchedulerHint

func SchedulerHintFromCode added in v1.1.0

func SchedulerHintFromCode(code uint64) SchedulerHint

type Scope

type Scope uint8

Scope identifies whether an error belongs to the session or a stream.

const (
	ScopeUnknown Scope = iota
	ScopeSession
	ScopeStream
)

func (Scope) String

func (s Scope) String() string

type SendStream

type SendStream interface {
	io.Writer
	io.Closer
	StreamID() uint64
	OpenInfo() []byte
	LocalAddr() net.Addr
	RemoteAddr() net.Addr
	Metadata() StreamMetadata
	UpdateMetadata(update MetadataUpdate) error
	WriteFinal(p []byte) (int, error)
	WritevFinal(parts ...[]byte) (int, error)
	CloseWrite() error
	CancelWrite(code uint64) error
	CloseWithError(code uint64, reason string) error
	SetDeadline(t time.Time) error
	SetWriteDeadline(t time.Time) error
}

SendStream is the stable send-only stream interface.

type Session

type Session interface {
	io.Closer
	AcceptStream(ctx context.Context) (Stream, error)
	AcceptUniStream(ctx context.Context) (RecvStream, error)
	OpenStream(ctx context.Context) (Stream, error)
	OpenUniStream(ctx context.Context) (SendStream, error)
	OpenStreamWithOptions(ctx context.Context, opts OpenOptions) (Stream, error)
	OpenUniStreamWithOptions(ctx context.Context, opts OpenOptions) (SendStream, error)
	OpenAndSend(ctx context.Context, p []byte) (Stream, int, error)
	OpenAndSendWithOptions(ctx context.Context, opts OpenOptions, p []byte) (Stream, int, error)
	OpenUniAndSend(ctx context.Context, p []byte) (SendStream, int, error)
	OpenUniAndSendWithOptions(ctx context.Context, opts OpenOptions, p []byte) (SendStream, int, error)
	CloseWithError(err error)
	Wait(ctx context.Context) error
	Closed() bool
	State() SessionState
	Stats() SessionStats
}

Session is the stable session interface used by native zmux and adapters.

func AsSession

func AsSession(conn *Conn) Session

AsSession wraps a native *Conn as a stable Session.

func ClientIOSession added in v1.1.2

func ClientIOSession(reader io.Reader, writer io.Writer, cfg *Config) (Session, error)

ClientIOSession returns a stable initiator Session backed by native zmux on separate reader and writer halves.

func ClientSession

func ClientSession(conn io.ReadWriteCloser, cfg *Config) (Session, error)

ClientSession returns a stable initiator Session backed by native zmux.

func NewIOSession added in v1.1.2

func NewIOSession(reader io.Reader, writer io.Writer, cfg *Config) (Session, error)

NewIOSession returns a stable Session backed by native zmux on separate reader and writer halves.

func NewSession

func NewSession(conn io.ReadWriteCloser, cfg *Config) (Session, error)

NewSession returns a stable Session backed by native zmux.

func ServerIOSession added in v1.1.2

func ServerIOSession(reader io.Reader, writer io.Writer, cfg *Config) (Session, error)

ServerIOSession returns a stable responder Session backed by native zmux on separate reader and writer halves.

func ServerSession

func ServerSession(conn io.ReadWriteCloser, cfg *Config) (Session, error)

ServerSession returns a stable responder Session backed by native zmux.

type SessionState

type SessionState uint8

SessionState is the public session lifecycle state.

const (
	SessionStateInvalid SessionState = iota
	SessionStateReady
	SessionStateDraining
	SessionStateClosing
	SessionStateClosed
	SessionStateFailed
)

func (SessionState) String

func (s SessionState) String() string

func (SessionState) Terminal

func (s SessionState) Terminal() bool

Terminal reports whether s is final.

func (SessionState) Valid

func (s SessionState) Valid() bool

Valid reports whether s is a defined public session state.

type SessionStats

type SessionStats struct {
	State                    SessionState
	KeepaliveInterval        time.Duration
	KeepaliveMaxPingInterval time.Duration
	KeepaliveTimeout         time.Duration
	PingOutstanding          bool
	PingStalled              bool
	Progress                 ProgressStats
	LastInboundFrameAt       time.Time
	LastControlProgress      time.Time
	LastTransportWrite       time.Time
	LastStreamProgress       time.Time
	LastAppProgress          time.Time
	LastPingSentAt           time.Time
	LastPongAt               time.Time
	LastPingRTT              time.Duration

	ActiveStreams     ActiveStreamStats
	Queues            QueueStats
	Flush             FlushStats
	BlockedWriteTotal time.Duration
	LastOpenLatency   time.Duration
	Pressure          PressureStats
	Hidden            HiddenStats
	AcceptBacklog     AcceptBacklogStats
	Provisionals      ProvisionalStats
	Reasons           ReasonStats
	Diagnostics       DiagnosticStats
}

SessionStats is a snapshot of session state and runtime counters.

type SettingID

type SettingID = wire.SettingID

type Settings

type Settings = wire.Settings

func DefaultSettings

func DefaultSettings() Settings

type Source

type Source uint8

Source identifies where the error came from.

const (
	SourceUnknown Source = iota
	SourceLocal
	SourceRemote
	SourceTransport
)

func (Source) String

func (s Source) String() string

type Stream

type Stream interface {
	net.Conn
	StreamID() uint64
	OpenInfo() []byte
	Metadata() StreamMetadata
	UpdateMetadata(update MetadataUpdate) error
	WriteFinal(p []byte) (int, error)
	WritevFinal(parts ...[]byte) (int, error)
	CloseRead() error
	CancelRead(code uint64) error
	CloseWrite() error
	CancelWrite(code uint64) error
	CloseWithError(code uint64, reason string) error
}

Stream is the stable bidirectional stream interface.

type StreamMetadata

type StreamMetadata struct {
	Priority uint64
	Group    *uint64
	OpenInfo []byte
}

StreamMetadata is the advisory metadata currently known for a stream.

type StreamMetadataType

type StreamMetadataType = wire.StreamMetadataType

type TLV

type TLV = wire.TLV

func ParseTLVs

func ParseTLVs(src []byte) ([]TLV, error)

type TerminationKind

type TerminationKind uint8

TerminationKind identifies how the operation terminated.

const (
	TerminationUnknown TerminationKind = iota
	TerminationGraceful
	TerminationStopped
	TerminationReset
	TerminationAbort
	TerminationSessionTermination
)

func (TerminationKind) String

func (k TerminationKind) String() string

type WireError

type WireError = wire.Error

type WriteHalf

type WriteHalf interface {
	io.Writer
	CloseWrite() error
	SetWriteDeadline(time.Time) error
	LocalAddr() net.Addr
	RemoteAddr() net.Addr
}

WriteHalf is the minimal directional write-side contract required by JoinedConn.

Directories

Path Synopsis
adapter
quicmux module
internal
runtime
Package runtime contains internal scheduling, queueing, and policy helpers.
Package runtime contains internal scheduling, queueing, and policy helpers.
state
Package state contains internal stream and session state helpers.
Package state contains internal stream and session state helpers.
wire
Package wire contains internal codecs, framing, TLV, and preface helpers.
Package wire contains internal codecs, framing, TLV, and preface helpers.
seal module
zmuxh3 module
zmuxquic module
zmuxws module

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL