zmux

package module
v1.0.9 Latest Latest
Warning

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

Go to latest
Published: Apr 27, 2026 License: Apache-2.0 Imports: 19 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 implements the zmux v1 single-link stream multiplexing protocol in Go.

It provides:

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

Constructors

Use the native constructors when you want 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.

Use the stable constructors when you want the transport-agnostic surface:

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

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

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

Stable Interfaces

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 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 local/native 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 only need to implement the stable surfaces.

Basic Use

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

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 existing 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 on bidirectional and unidirectional streams, 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.

Configuration

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

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

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

Start from DefaultConfig() unless you intentionally want to override fields that have non-default zero values such as Role.

DefaultConfig() already enables a low-frequency directional-idle keepalive probe plus a slower cap on how long the session may go without sending any PING for RTT sampling. Set KeepaliveInterval = 0 to disable the automatic keepalive logic entirely, or lower it when you want faster liveness detection.

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 your transport exposes separate read and write halves, combine them first:

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

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.

The package exposes repository-default Session, Stream, SendStream, and RecvStream interfaces for opening, accepting, reading, writing, and closing multiplexed streams over a single transport connection.

The root package is the supported integration surface. Wire codec logic, protocol-state helpers, and repository-default runtime policy remain in shallow internal packages:

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

Library users should treat those internal packages as implementation details rather than import contracts.

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 (
	CapabilityPriorityHints         = wire.CapabilityPriorityHints
	CapabilityStreamGroups          = wire.CapabilityStreamGroups
	CapabilityMultilinkBasicRetired = wire.CapabilityMultilinkBasicRetired
	CapabilityMultilinkBasic        = wire.CapabilityMultilinkBasic
	CapabilityPriorityUpdate        = wire.CapabilityPriorityUpdate
	CapabilityOpenMetadata          = wire.CapabilityOpenMetadata
)
View Source
const (
	SettingInitialMaxStreamDataBidiLocallyOpened = wire.SettingInitialMaxStreamDataBidiLocallyOpened
	SettingInitialMaxStreamDataBidiPeerOpened    = wire.SettingInitialMaxStreamDataBidiPeerOpened
	SettingInitialMaxStreamDataUni               = wire.SettingInitialMaxStreamDataUni
	SettingInitialMaxData                        = wire.SettingInitialMaxData
	SettingMaxIncomingStreamsBidi                = wire.SettingMaxIncomingStreamsBidi
	SettingMaxIncomingStreamsUni                 = wire.SettingMaxIncomingStreamsUni
	SettingMaxFramePayload                       = wire.SettingMaxFramePayload
	SettingIdleTimeoutMillis                     = wire.SettingIdleTimeoutMillis
	SettingKeepaliveHintMillis                   = wire.SettingKeepaliveHintMillis
	SettingMaxControlPayloadBytes                = wire.SettingMaxControlPayloadBytes
	SettingMaxExtensionPayloadBytes              = wire.SettingMaxExtensionPayloadBytes
	SettingSchedulerHints                        = wire.SettingSchedulerHints
)
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 (
	EXTPriorityUpdate     = wire.EXTPriorityUpdate
	ExtMLReadyRetired     = wire.ExtMLReadyRetired
	ExtMLAttachRetired    = wire.ExtMLAttachRetired
	ExtMLAttachAckRetired = wire.ExtMLAttachAckRetired
	ExtMLDrainReqRetired  = wire.ExtMLDrainReqRetired
	ExtMLDrainAckRetired  = wire.ExtMLDrainAckRetired
)
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
)

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 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 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 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    Capabilities
	Settings        Settings
	NonceSource     io.Reader
	// KeepaliveInterval bounds how long inbound or outbound transport activity
	// may stay idle before the runtime probes with PING. Zero disables automatic
	// keepalive entirely, including KeepaliveMaxPingInterval.
	KeepaliveInterval time.Duration
	// KeepaliveMaxPingInterval bounds how long the runtime may go without
	// sending any local PING while keepalive is enabled. It is useful for
	// occasional RTT sampling even on continuously busy sessions. Zero disables
	// this extra cap and relies only on directional idle probing.
	KeepaliveMaxPingInterval time.Duration
	// KeepaliveTimeout bounds how long an outstanding keepalive ping may remain
	// unanswered before the session is aborted. When left at zero, the runtime
	// derives an adaptive default from the keepalive interval and observed RTT
	// within bounded caps so very high latency links remain usable.
	KeepaliveTimeout time.Duration

	// SessionMemoryCap overrides the repository-default tracked-session-memory
	// hard cap. Zero uses the repository default.
	SessionMemoryCap uint64
	// PerStreamQueuedDataHWM overrides the repository-default per-stream
	// ordinary queued-data high watermark. Zero uses the repository default.
	PerStreamQueuedDataHWM uint64
	// SessionQueuedDataHWM overrides the repository-default session-wide
	// ordinary queued-data high watermark. Zero uses the repository default.
	SessionQueuedDataHWM uint64
	// UrgentQueuedBytesCap overrides the repository-default urgent/control lane
	// hard cap. Zero uses the repository default.
	UrgentQueuedBytesCap uint64
	// PendingControlBytesBudget overrides the repository-default coalesced
	// pending control-plane byte budget. Zero uses the repository default.
	PendingControlBytesBudget uint64
	// PendingPriorityBytesBudget overrides the repository-default coalesced
	// pending advisory byte budget. Zero uses the repository default.
	PendingPriorityBytesBudget uint64
	// RetainedOpenInfoBytesBudget overrides the repository-default retained
	// open_info byte budget. Zero uses the repository default.
	RetainedOpenInfoBytesBudget uint64
	// RetainedPeerReasonBytesBudget overrides the repository-default retained
	// peer reason-text byte budget. Zero uses the repository default.
	RetainedPeerReasonBytesBudget uint64
	// AggregateLateDataCap overrides the repository-default aggregate late-data
	// accounting cap. Zero uses the repository default.
	AggregateLateDataCap uint64
	// AcceptBacklogLimit overrides the repository-default visible accept backlog
	// count cap. Zero uses the repository default.
	AcceptBacklogLimit int
	// AcceptBacklogBytesLimit overrides the repository-default visible accept
	// backlog byte cap. Zero uses the repository default.
	AcceptBacklogBytesLimit uint64
	// TombstoneLimit overrides the repository-default retained tombstone count
	// limit. Zero uses the repository default.
	TombstoneLimit int
	// MarkerOnlyUsedStreamLimit overrides the repository-default maximum count
	// of retained marker-only used-stream entries after tombstones have been
	// compacted or reaped. Zero uses the repository-default derived cap.
	MarkerOnlyUsedStreamLimit int
	// AbuseWindow overrides the repository-default local anti-abuse accounting
	// window. Zero uses the repository default.
	AbuseWindow time.Duration
	// HiddenAbortChurnWindow overrides the repository-default hidden abort churn
	// detection window. Zero uses the repository default.
	HiddenAbortChurnWindow time.Duration
	// HiddenAbortChurnThreshold overrides the repository-default hidden
	// open-then-abort churn threshold. Zero uses the repository default.
	HiddenAbortChurnThreshold uint32
	// VisibleTerminalChurnWindow overrides the repository-default visible churn
	// detection window. Zero uses the repository default.
	VisibleTerminalChurnWindow time.Duration
	// VisibleTerminalChurnThreshold overrides the repository-default visible
	// open-then-reset/abort churn threshold. Zero uses the repository default.
	VisibleTerminalChurnThreshold uint32
	// InboundControlFrameBudget overrides the repository-default inbound
	// control-frame rolling window budget. Zero uses the repository default.
	InboundControlFrameBudget uint32
	// InboundControlBytesBudget overrides the repository-default inbound
	// control-byte rolling window budget. Zero uses the repository default.
	InboundControlBytesBudget uint64
	// InboundExtFrameBudget overrides the repository-default inbound EXT-frame
	// rolling window budget. Zero uses the repository default.
	InboundExtFrameBudget uint32
	// InboundExtBytesBudget overrides the repository-default inbound EXT-byte
	// rolling window budget. Zero uses the repository default.
	InboundExtBytesBudget uint64
	// InboundMixedFrameBudget overrides the repository-default mixed
	// control/EXT frame rolling window budget. Zero uses the repository default.
	InboundMixedFrameBudget uint32
	// InboundMixedBytesBudget overrides the repository-default mixed
	// control/EXT byte rolling window budget. Zero uses the repository default.
	InboundMixedBytesBudget uint64
	// NoOpControlFloodThreshold overrides the repository-default mixed no-op
	// control threshold. Zero uses the repository default.
	NoOpControlFloodThreshold uint32
	// NoOpMaxDataFloodThreshold overrides the repository-default no-op MAX_DATA
	// threshold. Zero uses the repository default.
	NoOpMaxDataFloodThreshold uint32
	// NoOpBlockedFloodThreshold overrides the repository-default no-op BLOCKED
	// threshold. Zero uses the repository default.
	NoOpBlockedFloodThreshold uint32
	// NoOpZeroDataFloodThreshold overrides the repository-default zero-length
	// DATA threshold. Zero uses the repository default.
	NoOpZeroDataFloodThreshold uint32
	// NoOpPriorityUpdateFloodThreshold overrides the repository-default no-op
	// PRIORITY_UPDATE threshold. Zero uses the repository default.
	NoOpPriorityUpdateFloodThreshold uint32
	// GroupRebucketChurnThreshold overrides the repository-default repeated
	// effective stream_group rebucketing threshold within the local
	// anti-abuse window when the negotiated scheduler baseline is group_fair.
	// Zero uses the repository default.
	GroupRebucketChurnThreshold uint32
	// InboundPingFloodThreshold overrides the repository-default inbound PING
	// flood threshold. Zero uses the repository default.
	InboundPingFloodThreshold uint32
	// StopSendingGracefulDrainWindow overrides the repository-default bounded
	// graceful-drain admission window used after peer STOP_SENDING before
	// falling back to RESET(CANCELLED). Zero uses the repository default. When
	// left unset, the runtime may widen the effective window from observed RTT
	// within bounded caps so high latency links do not spuriously reset streams.
	StopSendingGracefulDrainWindow time.Duration
	// StopSendingGracefulTailCap overrides the repository-default maximum
	// unavoidable tail, in bytes, that may still converge via DATA|FIN after
	// peer STOP_SENDING. Zero uses the repository default.
	StopSendingGracefulTailCap uint64
	// GracefulCloseDrainTimeout overrides the repository-default bounded
	// graceful-close drain wait before Close reports timeout to the caller.
	// This bounds how long Close will keep waiting for already-visible local
	// streams and provisionals to converge after GOAWAY, so it should usually be
	// tuned from application shutdown behavior rather than raw RTT alone. Zero
	// uses the repository default; when left unset, the runtime may widen the
	// effective wait from observed RTT within bounded caps while keeping the
	// default tuned for ordinary moderate-latency links.
	GracefulCloseDrainTimeout time.Duration

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

Config controls session establishment and runtime behavior.

Prefer starting from DefaultConfig(). The zero value is not the repository default configuration because Role zero is RoleInitiator and the repository defaults also enable low-frequency idle keepalive probing plus a slower RTT sampling cap.

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns the repository-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 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 New

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

New establishes a native zmux session.

func Server

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

Server establishes a native responder session.

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 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 an independent read half plus write half into a net.Conn.

Either half may be nil. A nil read half makes Read return ErrStreamNotReadable. A nil write half makes Write return ErrStreamNotWritable.

Directional pause operations hand ownership of the currently attached half to the caller. While paused, upper-layer operations in that direction block until the handle resumes or the joined-level deadline/close wakes them. Close only closes halves that are still attached at the time Close runs; detached halves remain caller-owned.

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 (*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 repository-default 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

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 ClientSession

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

ClientSession returns a stable initiator Session backed by native zmux.

func NewSession

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

NewSession returns a stable Session backed by native zmux.

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, batching, and repository-default runtime policy helpers used by the public zmux package.
Package runtime contains internal scheduling, queueing, batching, and repository-default runtime policy helpers used by the public zmux package.
state
Package state contains internal protocol-state helpers used by the public zmux package.
Package state contains internal protocol-state helpers used by the public zmux package.
wire
Package wire contains internal codec, registry, framing, TLV, and preface helpers used by the public zmux package.
Package wire contains internal codec, registry, framing, TLV, and preface helpers used by the public zmux package.
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