Documentation
¶
Overview ¶
Package uio provides event-driven connections whose native Unix data path runs in serialized connection tasks outside epoll/kqueue loops.
Index ¶
- Constants
- Variables
- func FindLayer[T any](conn Lower) (T, bool)
- func OnTurn() bool
- func ReleaseBuffer(buffer *Buffer)
- func WithDialControl(control SocketControl) dialControlOption
- func WithLayers(layers ...Layer) layersOption
- func WithListenControl(control SocketControl) listenControlOption
- func WithLocalAddr(addr string) localAddrOption
- func WithUserdata(value any) userdataOption
- func WriteShared(conn Lower, sb *SharedBuffer) (int, error)
- type AdoptOption
- type BlockingConn
- func (bc *BlockingConn) Abort(cause error) error
- func (bc *BlockingConn) Close() error
- func (bc *BlockingConn) CloseWrite() error
- func (bc *BlockingConn) Flush() error
- func (bc *BlockingConn) FlushContext(ctx context.Context) error
- func (bc *BlockingConn) InternalWriter() *blockio.Writer
- func (bc *BlockingConn) LocalAddr() net.Addr
- func (bc *BlockingConn) Read(p []byte) (int, error)
- func (bc *BlockingConn) ReadFrom(r io.Reader) (int64, error)
- func (bc *BlockingConn) Reader() *BlockingReader
- func (bc *BlockingConn) RemoteAddr() net.Addr
- func (bc *BlockingConn) SetDeadline(t time.Time) error
- func (bc *BlockingConn) SetReadDeadline(t time.Time) error
- func (bc *BlockingConn) SetWriteDeadline(t time.Time) error
- func (bc *BlockingConn) Unwrap() Conn
- func (bc *BlockingConn) Write(p []byte) (int, error)
- func (bc *BlockingConn) WriteContext(ctx context.Context, p []byte) (int, error)
- func (bc *BlockingConn) WriteShared(sb *SharedBuffer) (int, error)
- func (bc *BlockingConn) WriteSharedContext(ctx context.Context, sb *SharedBuffer) (int, error)
- func (bc *BlockingConn) WriteTo(w io.Writer) (int64, error)
- func (bc *BlockingConn) Writer() *BlockingWriter
- type BlockingOption
- type BlockingReader
- type BlockingWriter
- func (w *BlockingWriter) Buffered() int
- func (w *BlockingWriter) Flush() error
- func (w *BlockingWriter) FlushContext(ctx context.Context) error
- func (w *BlockingWriter) InternalWriter() *blockio.Writer
- func (w *BlockingWriter) ReadFrom(r io.Reader) (int64, error)
- func (w *BlockingWriter) SetWriteDeadline(t time.Time) error
- func (w *BlockingWriter) Write(p []byte) (int, error)
- func (w *BlockingWriter) WriteContext(ctx context.Context, p []byte) (int, error)
- func (w *BlockingWriter) WriteOwned(buf *Buffer) (int, error)
- func (w *BlockingWriter) WriteOwnedContext(ctx context.Context, buf *Buffer) (int, error)
- func (w *BlockingWriter) WriteShared(sb *SharedBuffer) (int, error)
- func (w *BlockingWriter) WriteSharedContext(ctx context.Context, sb *SharedBuffer) (int, error)
- func (w *BlockingWriter) Writev(vec [][]byte) (int, error)
- func (w *BlockingWriter) WritevContext(ctx context.Context, vec [][]byte) (int, error)
- type Buffer
- type CloseWriter
- type CompositeBuffer
- type Conn
- type ConnState
- type DialOption
- type Dialer
- type Events
- func (ev *Events) Adopt(conn net.Conn, opts ...AdoptOption) (Conn, error)
- func (ev *Events) AdoptContext(ctx context.Context, conn net.Conn, opts ...AdoptOption) (Conn, error)
- func (ev *Events) Close(err error) error
- func (ev *Events) Dial(addr string, opts ...DialOption) (Conn, error)
- func (ev *Events) DialContext(dialCtx context.Context, addr string, opts ...DialOption) (Conn, error)
- func (ev *Events) Dialer(opts ...DialOption) (*Dialer, error)
- func (ev *Events) Listen(addr string, opts ...ListenOption) (Listener, error)
- func (ev *Events) Serve(addrs ...string) (err error)
- func (ev *Events) Stats() Stats
- func (ev *Events) Wait() error
- type Executor
- type FuncHandler
- func (h FuncHandler) OnBytesRead(c Conn, n int)
- func (h FuncHandler) OnBytesWritten(c Conn, n int)
- func (h FuncHandler) OnClose(c Conn, err error)
- func (h FuncHandler) OnOpen(c Conn)
- func (h FuncHandler) OnRead(c Conn) error
- func (h FuncHandler) OnStart(ev *Events)
- func (h FuncHandler) OnStop(ev *Events)
- func (h FuncHandler) OnTimer(c Conn) error
- type Handler
- type IOTask
- type Layer
- type LayerCloser
- type LayerContext
- type LayerFunc
- type LayerHandler
- type ListenOption
- type Listener
- type Lower
- type OutboundHolder
- type PacketLayer
- type PacketListener
- type PassThrough
- type ReadController
- type ServeHooks
- type SharedBuffer
- type SocketConn
- type SocketControl
- type Stats
- type TrafficObserver
- type UnflushedError
- type Unwrapper
- type Upper
Constants ¶
const DefaultBlockingBuffer = blockio.DefaultWindow
DefaultBlockingBuffer is the default per-direction buffer limit (64 KiB) for BlockingReader and BlockingWriter when Events does not specify a limit.
const DefaultDeliverBound = 64 << 10
DefaultDeliverBound bounds what one layer delivers to the layer above before that layer reads — each layer's delivery, whichever way the stack is stacked. Events.MaxInboundBuffered, when set, is the bound instead.
const LingerTimeout = 5 * time.Second
LingerTimeout bounds how long a graceful close — [Conn.Close] — waits for its output without progress before it closes with what remains.
Variables ¶
var ( ErrOutboundOverflow = errors.New("uio: outbound buffer limit exceeded") ErrInboundOverflow = errors.New("uio: inbound buffer limit exceeded") ErrUnflushedData = errors.New("uio: connection closed with unflushed data") ErrDialOnEventLoop = errors.New("uio: Dial cannot run on an event loop") // ErrFirstTurnRefused reports an Executor that declined to run a dialed // or adopted connection's first turn, so the connection closed without // ever calling back. ErrFirstTurnRefused = errors.New("uio: the executor refused the connection's first turn") // ErrPeerExists reports DialPeer finding the peer already connected. ErrPeerExists = errors.New("uio: peer already connected") )
var ErrBlockingOnTurn = blockio.ErrBlockingOnTurn
ErrBlockingOnTurn reports an attempt to invoke a blocking read or write on a connection turn or event-loop goroutine.
var ErrEventsStarted = errors.New("uio: Events.Serve was already called")
ErrEventsStarted reports a second Serve on one Events: an Events starts once, and a Serve that found it running or finished returns this.
var ErrLayersNeedStream = errors.New("uio: layers carry streams, not packet connections")
ErrLayersNeedStream reports a packet connection — UDP, IP, unixgram, unixpacket — on an endpoint whose layer chain does not start with a PacketLayer: a layer carries a byte stream, and only a PacketLayer takes a packet connection's messages, boundaries kept.
var ErrUnsupported = readcontrol.ErrUnsupported
ErrUnsupported reports a method this connection cannot carry: CloseWrite on a datagram or stdio connection, or on a layered one whose layers do not implement CloseWriter; a deadline or an option the backend has no way to honor.
Functions ¶
func FindLayer ¶ added in v1.8.0
FindLayer returns the first LayerHandler of type T at or below conn — starting with the layer that built conn, down to the socket: the TLS state under a WebSocket layer:
tls, ok := uio.FindLayer[interface{ State() tls.ConnectionState }](conn)
func OnTurn ¶ added in v1.9.0
func OnTurn() bool
OnTurn reports whether the calling goroutine is currently executing inside an event-loop or connection-turn callback, where blocking I/O must not block.
func ReleaseBuffer ¶ added in v1.1.0
func ReleaseBuffer(buffer *Buffer)
ReleaseBuffer returns an unsubmitted buffer to the pool. It must be called at most once, and the buffer must not be used afterward.
func WithDialControl ¶ added in v1.8.0
func WithDialControl(control SocketControl) dialControlOption
WithDialControl runs control on the dialing socket's descriptor, after the socket is created and before WithLocalAddr binds it or it connects — as net.Dialer's Control does, so a bind-time option such as SO_REUSEPORT can be set.
func WithLayers ¶ added in v1.8.0
func WithLayers(layers ...Layer) layersOption
WithLayers runs this endpoint with its own chain instead of none — the layers given, in install order, the first closest to the wire. A Listen gives its listener the chain; a dial, or one Dialer call, gives that connection. On a Dialer call it replaces the Dialer's own chain for that call. WithLayers() with no layers runs the layer that changes nothing (PassThroughLayer), so a chain always has a layer.
func WithListenControl ¶ added in v1.8.0
func WithListenControl(control SocketControl) listenControlOption
WithListenControl runs control on the listening socket's descriptor before it binds. With ReusePort it runs after the sharing option itself was set.
func WithLocalAddr ¶ added in v1.8.0
func WithLocalAddr(addr string) localAddrOption
WithLocalAddr binds the dial's socket to addr before it connects, in the address syntax of the network dialed: "127.0.0.1:0", "[::1]:0", "unix:///tmp/app.rnd". A second dial from the same address fails unless the option set on the socket allows the sharing.
func WithUserdata ¶ added in v1.8.0
func WithUserdata(value any) userdataOption
WithUserdata sets the connection's initial Userdata: for a dial or an adoption, that one connection's; for a Listen, every connection it accepts. A Dialer's default is each of its dials', and a dial's own WithUserdata overrides it.
func WriteShared ¶ added in v1.9.0
func WriteShared(conn Lower, sb *SharedBuffer) (int, error)
WriteShared submits sb to conn without copying payload bytes on stream connections (and transparently passes through any protocol Layer stack or multiplexed stream). Reference counting is handled internally across all success, backpressure (ErrOutboundOverflow), and close paths.
Types ¶
type AdoptOption ¶ added in v1.8.0
type AdoptOption interface {
// contains filtered or unexported methods
}
AdoptOption configures one adoption; see Adopt.
type BlockingConn ¶ added in v1.9.0
type BlockingConn struct {
// contains filtered or unexported fields
}
BlockingConn wraps a stream Conn with its BlockingReader and BlockingWriter to satisfy the standard library's net.Conn, io.ReaderFrom, and io.WriterTo interfaces.
func NewBlockingConn ¶ added in v1.9.0
func NewBlockingConn(c Conn, opts ...BlockingOption) (*BlockingConn, error)
NewBlockingConn switches c's inbound direction to pull mode and returns a standard net.Conn backed by c's BlockingReader and BlockingWriter.
func (*BlockingConn) Abort ¶ added in v1.9.0
func (bc *BlockingConn) Abort(cause error) error
func (*BlockingConn) Close ¶ added in v1.9.0
func (bc *BlockingConn) Close() error
func (*BlockingConn) CloseWrite ¶ added in v1.9.0
func (bc *BlockingConn) CloseWrite() error
func (*BlockingConn) Flush ¶ added in v1.9.0
func (bc *BlockingConn) Flush() error
func (*BlockingConn) FlushContext ¶ added in v1.9.0
func (bc *BlockingConn) FlushContext(ctx context.Context) error
func (*BlockingConn) InternalWriter ¶ added in v1.9.0
func (bc *BlockingConn) InternalWriter() *blockio.Writer
func (*BlockingConn) LocalAddr ¶ added in v1.9.0
func (bc *BlockingConn) LocalAddr() net.Addr
func (*BlockingConn) ReadFrom ¶ added in v1.9.0
func (bc *BlockingConn) ReadFrom(r io.Reader) (int64, error)
func (*BlockingConn) Reader ¶ added in v1.9.0
func (bc *BlockingConn) Reader() *BlockingReader
func (*BlockingConn) RemoteAddr ¶ added in v1.9.0
func (bc *BlockingConn) RemoteAddr() net.Addr
func (*BlockingConn) SetDeadline ¶ added in v1.9.0
func (bc *BlockingConn) SetDeadline(t time.Time) error
SetDeadline sets both the read and write blocking wait deadlines without closing the underlying connection when they expire.
func (*BlockingConn) SetReadDeadline ¶ added in v1.9.0
func (bc *BlockingConn) SetReadDeadline(t time.Time) error
func (*BlockingConn) SetWriteDeadline ¶ added in v1.9.0
func (bc *BlockingConn) SetWriteDeadline(t time.Time) error
func (*BlockingConn) Unwrap ¶ added in v1.9.0
func (bc *BlockingConn) Unwrap() Conn
func (*BlockingConn) WriteContext ¶ added in v1.9.0
func (*BlockingConn) WriteShared ¶ added in v1.9.0
func (bc *BlockingConn) WriteShared(sb *SharedBuffer) (int, error)
func (*BlockingConn) WriteSharedContext ¶ added in v1.9.0
func (bc *BlockingConn) WriteSharedContext(ctx context.Context, sb *SharedBuffer) (int, error)
func (*BlockingConn) WriteTo ¶ added in v1.9.0
func (bc *BlockingConn) WriteTo(w io.Writer) (int64, error)
func (*BlockingConn) Writer ¶ added in v1.9.0
func (bc *BlockingConn) Writer() *BlockingWriter
type BlockingOption ¶ added in v1.9.0
type BlockingOption interface {
// contains filtered or unexported methods
}
BlockingOption configures a BlockingReader, BlockingWriter, or BlockingConn.
func WithBufferSize ¶ added in v1.9.0
func WithBufferSize(bytes int) BlockingOption
WithBufferSize sets the buffer window (in bytes) for a BlockingReader, BlockingWriter, or BlockingConn. Values <= 0 leave the default window in effect.
type BlockingReader ¶ added in v1.9.0
type BlockingReader struct {
// contains filtered or unexported fields
}
BlockingReader is the pull-mode blocking inbound endpoint of a stream Conn. It does not implement io.Closer; lifecycle ownership stays on Conn.
func NewBlockingReader ¶ added in v1.9.0
func NewBlockingReader(c Conn, opts ...BlockingOption) (*BlockingReader, error)
NewBlockingReader switches c's inbound direction from OnRead push callbacks to pull-mode blocking reads and returns its single *BlockingReader. Calling NewBlockingReader again on the same connection returns the same instance. Packet (UDP) connections return (nil, ErrUnsupported).
func (*BlockingReader) Buffered ¶ added in v1.9.0
func (r *BlockingReader) Buffered() int
Buffered reports unread bytes currently buffered in the reader's pipe.
func (*BlockingReader) Read ¶ added in v1.9.0
func (r *BlockingReader) Read(p []byte) (int, error)
Read reads up to len(p) bytes from the connection, blocking until data arrives, EOF is reached, the connection closes, or the read deadline expires.
func (*BlockingReader) SetReadDeadline ¶ added in v1.9.0
func (r *BlockingReader) SetReadDeadline(t time.Time) error
SetReadDeadline sets the deadline for blocked Read and WriteTo calls without closing the underlying connection when it expires.
type BlockingWriter ¶ added in v1.9.0
type BlockingWriter struct {
// contains filtered or unexported fields
}
BlockingWriter is the blocking outbound endpoint of a stream Conn. Multiple goroutines may invoke methods on a BlockingWriter concurrently, and it may coexist with non-blocking Conn.Write calls. It does not implement io.Closer.
func NewBlockingWriter ¶ added in v1.9.0
func NewBlockingWriter(c Conn, opts ...BlockingOption) (*BlockingWriter, error)
NewBlockingWriter returns c's single *BlockingWriter for backpressured blocking writes from application goroutines. Packet (UDP) connections return (nil, ErrUnsupported).
func (*BlockingWriter) Buffered ¶ added in v1.9.0
func (w *BlockingWriter) Buffered() int
Buffered reports accepted outbound bytes not yet flushed to the wire.
func (*BlockingWriter) Flush ¶ added in v1.9.0
func (w *BlockingWriter) Flush() error
Flush flushes queued outbound bytes and blocks until the outbound buffer drains, the connection closes, or the write deadline expires.
func (*BlockingWriter) FlushContext ¶ added in v1.9.0
func (w *BlockingWriter) FlushContext(ctx context.Context) error
FlushContext flushes queued outbound bytes and blocks until the outbound buffer drains, the connection closes, the write deadline expires, or ctx ends.
func (*BlockingWriter) InternalWriter ¶ added in v1.9.0
func (w *BlockingWriter) InternalWriter() *blockio.Writer
InternalWriter exposes the underlying blockio.Writer for zero-copy WriteTo relays.
func (*BlockingWriter) ReadFrom ¶ added in v1.9.0
func (w *BlockingWriter) ReadFrom(r io.Reader) (int64, error)
ReadFrom copies from r into the connection using pooled zero-copy WriteOwned buffers.
func (*BlockingWriter) SetWriteDeadline ¶ added in v1.9.0
func (w *BlockingWriter) SetWriteDeadline(t time.Time) error
SetWriteDeadline sets the deadline for blocked Write, ReadFrom, and Flush calls without closing the underlying connection when it expires.
func (*BlockingWriter) Write ¶ added in v1.9.0
func (w *BlockingWriter) Write(p []byte) (int, error)
Write writes all of p to the connection, suspending while the outbound window is full. Each call is atomic among BlockingWriter callers.
func (*BlockingWriter) WriteContext ¶ added in v1.9.0
WriteContext writes all of p to the connection, suspending until space is available, the connection closes, the write deadline expires, or ctx ends.
func (*BlockingWriter) WriteOwned ¶ added in v1.9.0
func (w *BlockingWriter) WriteOwned(buf *Buffer) (int, error)
WriteOwned transfers ownership of buf to the connection, suspending while the outbound window is full, and always consumes or releases buf.
func (*BlockingWriter) WriteOwnedContext ¶ added in v1.9.0
WriteOwnedContext transfers ownership of buf to the connection, suspending while the outbound window is full until space drains, the connection closes, the write deadline expires, or ctx ends. Always consumes or releases buf.
func (*BlockingWriter) WriteShared ¶ added in v1.9.0
func (w *BlockingWriter) WriteShared(sb *SharedBuffer) (int, error)
WriteShared writes sb to the connection using a zero-copy read-only view, suspending while the outbound window is full.
func (*BlockingWriter) WriteSharedContext ¶ added in v1.9.0
func (w *BlockingWriter) WriteSharedContext(ctx context.Context, sb *SharedBuffer) (int, error)
WriteSharedContext writes sb to the connection using a zero-copy read-only view, honoring ctx cancellation and deadlines while suspended.
func (*BlockingWriter) Writev ¶ added in v1.9.0
func (w *BlockingWriter) Writev(vec [][]byte) (int, error)
Writev writes all segments of vec atomically among BlockingWriter callers.
func (*BlockingWriter) WritevContext ¶ added in v1.9.0
WritevContext writes all segments of vec atomically among BlockingWriter callers, honoring ctx cancellation and deadlines while suspended.
type Buffer ¶ added in v1.1.0
Buffer is reusable byte storage that can be transferred to a connection with [Conn.WriteOwned]. Newly acquired writable capacity is not zeroed; every committed byte must be initialized. A Buffer must not be used after its ownership is transferred or it is released.
func AcquireBuffer ¶ added in v1.1.0
AcquireBuffer returns an empty pooled buffer with at least capacity bytes of writable space. Release it when ownership is not transferred to WriteOwned or FreezeBuffer.
type CloseWriter ¶ added in v1.8.0
type CloseWriter interface {
CloseWrite(ctx LayerContext) error
}
CloseWriter is implemented by a LayerHandler that can end one direction of its stream — a TLS close_notify sent before the socket's writing half shuts. It runs when the layer above calls CloseWrite. A layer without it does not support CloseWrite: a protocol that frames its bytes cannot leave its peer a stream it did not end itself. PassThroughLayer implements it by passing CloseWrite to the layer below (embedding PassThrough does not). UIO runs it once what was written before the call has gone below: writes still in flight into the layer finished, and what an OutboundHolder still holds sent — so the end never overtakes what it follows. Writes the call refused never reach the layer.
type CompositeBuffer ¶
type CompositeBuffer = bytebuf.CompositeBuffer
CompositeBuffer exposes UIO's pooled segmented buffer without introducing a second public buffer type.
type Conn ¶
type Conn interface {
Lower
// WriteTo drains inbound data; see Peek for the calling scope.
// Notice: non-blocking interface, should not be used as you use std.
io.WriterTo
// Close requests a graceful close and returns: everything accepted before
// the call leaves first, so the peer reads it whole. Writes are refused
// from the call (net.ErrClosed) while reads go on, and the connection's
// turn releases it once its queue is empty or LingerTimeout has passed
// without progress; on native Unix leftover output reaches OnClose as
// UnflushedError. On a layered connection each layer's OnClosing hook runs
// first. Calling Abort at any time cuts the drain short at once. Datagram
// connections have no stream queue to drain and release immediately.
io.Closer
// Abort requests an immediate close with cause and returns, cutting any
// graceful Close drain short at once. If cause is nil, net.ErrClosed is
// used. On native Unix the connection's turn releases it once any active
// callback has returned and reports unsent accepted payload as
// UnflushedError.
Abort(cause error) error
}
Conn is a connection managed by Events. On native Unix, socket I/O and callbacks run in the connection's turn, one serialized task outside the event loops, which only collect readiness. The stdio/Windows backend uses dedicated blocking I/O goroutines and serializes lifecycle callbacks per connection. Writes from other goroutines are safe and retain no caller-owned data after returning. Close and Abort return after the close request is accepted; OnClose is final. Native UDP writes send the datagram before returning, from any goroutine.
OS-level socket options and raw descriptor access live on SocketConn, obtained via SocketOf.
type ConnState ¶ added in v1.8.0
type ConnState uint32
ConnState reports where a connection's streams stand, as [Conn.State] and Lower.State report it. The bits are independent: a read-ended connection still writes, and a write-ended one still reads.
const ( // StateReadEnded reports that the peer ended its writing half and every // byte it sent was consumed — what Read(nil) reporting io.EOF says. StateReadEnded ConnState = 1 << iota // StateWriteEnded reports that this end's writing half was ended by // CloseWrite. StateWriteEnded // StateClosing reports a close begun — by either side — after which // writes are refused. A graceful close still reads until it releases. StateClosing // StateClosed reports the connection released: OnClose ran or is due. StateClosed )
type DialOption ¶ added in v1.8.0
type DialOption interface {
// contains filtered or unexported methods
}
DialOption configures one dial: the defaults of a Dialer, or one Dialer call's own. A Listen takes ListenOption, an adoption AdoptOption; WithLayers and WithUserdata are all three, the options a dial, a listen and an adoption share.
type Dialer ¶ added in v1.9.0
type Dialer struct {
// contains filtered or unexported fields
}
Dialer dials through one Events with private defaults — the options it was built with, a chain among them — which each Dial's own options override.
func (*Dialer) Dial ¶ added in v1.9.0
func (d *Dialer) Dial(addr string, opts ...DialOption) (Conn, error)
Dial dials addr with this Dialer; see DialContext.
func (*Dialer) DialContext ¶ added in v1.9.0
func (d *Dialer) DialContext(dialCtx context.Context, addr string, opts ...DialOption) (Conn, error)
DialContext connects synchronously through this Dialer's Events.
type Events ¶
type Events struct {
// Pollers is the number of event loops. On Unix each loop is one
// epoll or kqueue instance that a few goroutines wait on: they collect
// readiness for the connections and listeners registered with it and hand
// runnable connections to the Executor, and never run a callback. The
// default is one loop per four Ps, between one and eight, so a
// connection's events stay within one cluster of cores. The count
// follows GOMAXPROCS rather than NumCPU, so a process whose Ps are fewer
// than the machine's CPUs — a prefork child or a cgroup-limited container
// — sizes its loops to the Ps it runs on. On the stdio and Windows
// backend the loops only order registration and close.
Pollers int
// Executor supplies the native connection-round scheduler. When nil, UIO
// runs connection turns and write turns on sharded schedulers of its own
// (see internal/shardpool), both keyed by connection: by its event loop
// first, so the connections of one loop share a subset of the shards, and
// by its descriptor within that subset (see IOTask.ShardKey).
// When set, the executor lifecycle remains the caller's responsibility.
Executor Executor
// ReusePort indicates whether to set up the SO_REUSEPORT socket option.
// The default value is false.
ReusePort bool
// LockOSThread is used to determine whether each I/O event-loop is associated to an OS thread.
// The default value is false.
LockOSThread bool
// ReadBufferSize is the buffer size of each socket read. Native connection
// tasks may perform multiple reads per readiness event. The default is 4 KiB.
ReadBufferSize int
// WriteBufferedThreshold makes native callback writes smaller than this value
// join the connection's current outbound batch instead of attempting an
// immediate syscall. A connection task always flushes its batch before it
// finishes. Zero disables size-based buffering; a negative value also keeps
// it disabled. The stdio/Windows backend already writes through its dedicated
// asynchronous writer and does not use this threshold. The default is zero.
WriteBufferedThreshold int
// MaxOutboundBuffered limits accepted but unsent payload bytes per
// connection. It is a pure write budget: a write that would push buffered
// unsent data beyond the limit returns ErrOutboundOverflow, while reads
// keep flowing so a full-duplex peer can always drain its side. Callers
// treat overflow as overload — defer, drop, or close — and bound the
// receive side with MaxInboundBuffered. Zero disables the limit.
//
// With layers installed it bounds what the Handler writes: a write is
// refused before it enters the top layer when the queue below has no room
// for it, and what a layer writes below is never refused for size — a TLS
// record, once encrypted, must reach the wire. A write reserves its room
// as it enters, so concurrent writers cannot pass the limit together. The
// limit counts the Handler's bytes, so the queue can exceed it by what the
// layers add — a record's or a frame's few bytes of framing — and by the
// layers' own control output, a handshake or a ping.
MaxOutboundBuffered int
// BlockingWrite makes stream Conn.Write, WriteString, WriteByte, Writev and
// WriteOwned suspend calling application goroutines when the outbound queue
// is full (or chunk writes larger than MaxOutboundBuffered) instead of
// returning ErrOutboundOverflow, providing standard-library net.Conn write
// backpressure semantics. When enabled with MaxOutboundBuffered == 0, the
// outbound window defaults to DefaultBlockingBuffer (64 KiB).
//
// Event-loop and connection-turn callbacks (OnOpen, OnRead, OnTimer,
// OnBytesWritten) never block: if an on-turn write overflows the outbound
// limit, it still returns ErrOutboundOverflow immediately to prevent turn
// self-deadlock.
BlockingWrite bool
// MaxInboundBuffered bounds payload read but not yet consumed. Once
// callbacks leave this much unconsumed, the connection stops reading its
// socket, so TCP flow control slows the peer instead of the buffer
// growing; a Wake whose OnRead consumes below the limit reads again. The
// buffer exceeds the limit by at most one read. A ReserveInbound larger
// than the limit returns ErrInboundOverflow. Zero disables the limit.
//
// With layers installed it bounds what the layers hold for the Handler
// too: once they hold the limit unread, the stack takes nothing more from
// the socket, whose own buffer then fills to the limit and stops its
// reads. It is also each layer's delivery bound: a layer whose delivery
// to the layer above holds the limit is not called again until that layer
// reads, so a delivery passes it by one callback's write at most;
// DefaultDeliverBound stands in when this is zero. A connection holds at
// most twice the limit, and a layer's one delivery more.
// When zero, an explicitly consumer-paused layer stack also uses
// DefaultDeliverBound for its retained socket input until that hold drains.
//
// A packet connection has no socket buffer to hold and is never paced by
// this limit: its bottom [PacketLayer] carries whatever backpressure its
// protocol provides, and is called for every datagram that arrives.
MaxInboundBuffered int
// AllowHalfOpen keeps a stream connection open after its peer shuts its
// writing half. OnRead then runs once more, Read reports io.EOF once the
// buffered bytes are consumed, and the connection can still write; it
// closes once its own writing half is shut too, by CloseWrite, and Read
// reports io.EOF, or when it is closed. Bytes left unconsumed, say for a
// later Wake, keep it open until a callback consumes them. A reset after the end of the stream closes it on the native
// backend at once, and on the stdio backend at the next write. Without it,
// the end of the peer's stream closes the connection with io.EOF.
AllowHalfOpen bool
// Handler receives every connection's callbacks. A nil Handler leaves
// connections without callbacks, their input discarded.
Handler Handler
// Observer is told the bytes every connection reads and writes. Nil
// reports nothing.
Observer TrafficObserver
// Hooks runs around Serve. Nil runs nothing.
//
// Handler, Observer and Hooks are read once, when Serve starts.
Hooks ServeHooks
// contains filtered or unexported fields
}
Events owns listeners, event loops, the native connection-task scheduler, shared read buffers, and application callbacks for one server/dialer lifecycle. Configure it before Serve; an Events value is not restartable.
func (*Events) Adopt ¶ added in v1.9.0
Adopt transfers ownership of an established stream connection to ev. The caller must not use conn after calling Adopt, including when Adopt returns an error. ev must already be serving.
func (*Events) AdoptContext ¶ added in v1.9.0
func (ev *Events) AdoptContext(ctx context.Context, conn net.Conn, opts ...AdoptOption) (Conn, error)
AdoptContext is Adopt with ctx bounding the wait for any installed layers to open.
func (*Events) Close ¶
Close publishes shutdown and returns without waiting. Use Wait or the return of Serve as the lifecycle join point.
func (*Events) Dial ¶ added in v1.9.0
func (ev *Events) Dial(addr string, opts ...DialOption) (Conn, error)
Dial connects to the address on the named network.
Known networks are "tcp", "tcp4", "tcp6", "udp", "udp4", "udp6", "ip", "ip4", "ip6", "unix", "unixgram" and "unixpacket".
func (*Events) DialContext ¶ added in v1.9.0
func (ev *Events) DialContext(dialCtx context.Context, addr string, opts ...DialOption) (Conn, error)
DialContext connects synchronously and allows cancellation while resolving or establishing the connection. Never call it from an event loop goroutine. A connection it returns gets OnOpen and, at its end, OnClose, even if it is closed first; after an error no callback runs for it.
func (*Events) Dialer ¶ added in v1.9.0
func (ev *Events) Dialer(opts ...DialOption) (*Dialer, error)
Dialer returns a Dialer of ev with opts as its defaults.
func (*Events) Listen ¶ added in v1.8.0
func (ev *Events) Listen(addr string, opts ...ListenOption) (Listener, error)
Listen adds addr, in Serve's syntax, to a serving Events and accepts on it at once, with the Handler, Observer and options of the rest. Every connection accepted there starts with the Userdata a WithUserdata option names, the way a dial's names its connection's. opts configure this listener: the accepted connections' Userdata (WithUserdata), its chain (WithLayers) and its sockets (WithListenControl). With ReusePort, the address gets the group of listeners Serve would give it. A unix path is unlinked and bound afresh, taking the socket file over from whoever held it. Listen binds even from ServeHooks.OnStart, and accepting on such a listener starts once OnStart returns, so a server binds its ports and their chains before any callback runs. Before Serve has started, and once it is closing, Listen returns net.ErrClosed. Events.Close closes the listeners Listen added along with the others.
func (*Events) Serve ¶
Serve starts the event loops and listens on each supplied address. Calling Serve without an address starts a dial-only Events. An Events starts once: a second Serve, while the first runs or after it ended, returns ErrEventsStarted — the runtime, the loops and the acceptor are the first Serve's, and so is the completion of its lifecycle. A Serve that finds a Close before any other Serve returns net.ErrClosed: the close completed the idle lifecycle, and nothing starts.
func (*Events) Stats ¶ added in v1.9.0
Stats returns a point-in-time runtime snapshot of ev without allocating or taking any mutex. Safe to call concurrently from any goroutine before, during, or after Serve.
func (*Events) Wait ¶ added in v1.4.0
Wait blocks until Serve has stopped every loop and connection task, all stdio I/O goroutines have exited, and OnStop has returned. Wait may be called before Serve; Close before Serve completes it immediately. It must not be called from a callback that is itself part of the lifecycle being joined.
type Executor ¶ added in v1.4.0
Executor schedules native connection I/O rounds. Both methods must return promptly. SubmitBatch accepts a prefix and returns its length; every accepted task must run exactly once. Accepted tasks must run asynchronously after the submission method returns; inline execution would block the event loop and is unsupported. The batch slice is callback-scoped, so an executor must copy references it retains after SubmitBatch returns. Submit false means the task was not run; a short SubmitBatch result means the rejected suffix was not run. Rejection closes the affected connection, and what a refused turn still owes — OnClose, and OnBytesWritten for the close's final flush — runs on UIO's own goroutines, a few at a time, or inline on the rejecting goroutine when the executor also refuses that cleanup. A connection whose first turn is refused never got OnOpen, so it closes without OnClose too, and the Dial or Adopt that offered it reports ErrFirstTurnRefused. A native connection may have its connection turn and a write turn in flight at once; both arrive here.
type FuncHandler ¶ added in v1.8.0
type FuncHandler struct {
Open func(c Conn)
Read func(c Conn) error
Timer func(c Conn) error
Close func(c Conn, err error)
BytesRead func(c Conn, n int)
BytesWritten func(c Conn, n int)
Start func(ev *Events)
Stop func(ev *Events)
}
FuncHandler adapts plain functions to Handler, TrafficObserver and ServeHooks; set the value as whichever of Events.Handler, Observer and Hooks its fields fill. A nil field is a callback not set: a nil Read discards what each connection reads, a nil Timer never fires, and a nil BytesRead or BytesWritten reports nothing.
func (FuncHandler) OnBytesRead ¶ added in v1.8.0
func (h FuncHandler) OnBytesRead(c Conn, n int)
func (FuncHandler) OnBytesWritten ¶ added in v1.8.0
func (h FuncHandler) OnBytesWritten(c Conn, n int)
func (FuncHandler) OnClose ¶ added in v1.8.0
func (h FuncHandler) OnClose(c Conn, err error)
func (FuncHandler) OnOpen ¶ added in v1.8.0
func (h FuncHandler) OnOpen(c Conn)
func (FuncHandler) OnRead ¶ added in v1.8.0
func (h FuncHandler) OnRead(c Conn) error
func (FuncHandler) OnStart ¶ added in v1.8.0
func (h FuncHandler) OnStart(ev *Events)
func (FuncHandler) OnStop ¶ added in v1.8.0
func (h FuncHandler) OnStop(ev *Events)
func (FuncHandler) OnTimer ¶ added in v1.8.0
func (h FuncHandler) OnTimer(c Conn) error
type Handler ¶ added in v1.8.0
type Handler interface {
// OnOpen fires first for every connection, in the connection's first
// turn, also for one closed before that turn ran: OnClose follows, and
// writes from OnOpen return net.ErrClosed. On Unix a stream connection's
// first turn reads whatever its peer already sent right after OnOpen
// returns, in the same turn.
OnOpen(c Conn)
// OnRead fires on a turn once the connection opened, with inbound data
// available or none: a Wake or a released pause runs one too, so it may
// arrive with nothing to read. While read is paused it does not run;
// OnTimer and a stack's layer work go on. Inbound access methods are valid
// only for this callback invocation. An error closes the connection.
// A layer hears the same moment as its OnRead; here, at the top of the
// stack, outbound is Write, a method the Handler calls, which is why there
// is no OnWrite next to it.
OnRead(c Conn) error
// OnTimer fires on the turn the connection's own timer came due — the
// one SetWakeDeadline and SetWakeInterval arm — before OnRead in the same
// turn. An error closes the connection.
OnTimer(c Conn) error
// OnClose is the final callback for a connection and never overlaps its
// OnOpen or OnRead callback; only a connection that got OnOpen gets it.
// Close only requests the close: the connection is released, and OnClose
// runs, once the callback that closed it has returned.
//
// OnClose reports the connection released, not its socket closed. Where
// the native backend's event loops block in the kernel — GOMAXPROCS of 33
// or more, or Pollers above 8 — an accepted connection's socket is closed
// on a goroutine of its loop, so the peer can see the end shortly after
// OnClose ran; its descriptor number is not reused before then. A
// connection with a positive linger time (SocketConn.SetLinger), one that
// ran SocketConn.Control, and one accepted from a listener with a
// SocketControl close their socket before OnClose, as do dialed and adopted
// connections.
OnClose(c Conn, err error)
}
Handler receives the callbacks of every connection an Events serves or dials, set as Events.Handler. It is LayerHandler without OnWrite — the top of a stack, whose outbound is the Write method it calls. Lifecycle and data callbacks are serialized per connection, while callbacks for different connections may run concurrently. FuncHandler adapts plain functions to it.
type IOTask ¶ added in v1.4.0
type IOTask interface {
RunTask()
// ShardKey is the same for every task of one connection, its turns and
// its write turns alike, so an Executor that keeps a key's tasks on one
// worker keeps the connection's work, and the kernel's state for its
// socket, on one CPU. An Executor may ignore it.
ShardKey() uint32
}
IOTask is one native connection I/O round: either a connection turn, which reads and runs the connection's callbacks and is serialized per connection, or a write turn, which only sends output queued from outside those callbacks and may run beside the connection turn.
type Layer ¶ added in v1.8.0
type Layer interface {
// Attach builds the layer's state for one connection. The LayerContext
// stays valid until the connection's OnClose.
Attach(ctx LayerContext) LayerHandler
}
Layer is a protocol layer between the socket and the Handler: TLS, compression, an obfuscation, a handshake of its own. It transforms bytes — what arrives on its way up, what the Handler writes on its way down — and UIO carries everything else: the connection's turns, the Handler's callbacks, its addressing and deadlines, its closes. An endpoint stacks layers under the Events.Handler: WithLayers in a Events.Listen or in a dial names the chain its connections run.
A layer carries one connection: one connection above for each one below. A protocol that opens several streams over one connection — HTTP/2, QUIC — runs as the Handler, over a connection the layer below it made.
Attach runs once per connection and returns that connection's LayerHandler; the LayerContext it receives is the connection's place in the stack: the layer reads what arrived with Lower(), hands the layer above what that became with Upper().Write, and writes down with Lower().Write. The layer above — the next layer or the Handler — gets a Conn UIO builds over this one: its reads are what this layer delivered, its writes reach this layer's OnWrite, and everything else is the connection's own, passed through.
What UIO guarantees every layer, so that none has to remember it:
- Every turn reaches the layers above, whether or not anything was delivered, so their timers and wakes work through any stack.
- Each layer has a timer of its own (LayerContext.SetTimer and LayerContext.SetTimerInterval), and the Handler's [Conn.SetWakeDeadline] is a slot of its own too: no layer replaces another's.
- OnOpen, OnRead, OnTimer, OnClosing and OnClose run on the connection's turns, which never overlap one another or the callbacks of the layers above — the close walk runs on a turn whatever asked for it. The rest run on the goroutine that called for them, and may overlap the turns and one another: OnWrite on the writer's, CloseWrite on the one closing the connection, and OutboundHeld on a writer's. State they share with the turns needs a lock.
- UIO calls a layer only on a turn or from above it — the Handler, or the layer above through its LayerContext — never from below or from inside another layer's callback: a layer may hold its lock while it writes below, and nothing calls it back meanwhile. LayerContext.Open only records the request — the layers above open after the calling callback returned, on the same turn. A close a layer asks for (LayerContext.Close or Abort) likewise runs its OnClosing and the walk below on the turn, never inside the call; an end CloseWrite leaves waiting is passed down on one.
- Once the connection is closing — any layer, or the Handler, closed it — or ended, UIO starts no call into a layer, checking again after every callback: a write or flush that comes after returns net.ErrClosed, a repeated Close yields or reports net.ErrClosed, an Abort cuts any graceful drain short at once, and only OnClose follows. The close itself is the one caller left: the OnClosing hooks it walks below the layer that began it run while every layer already reads closing. A call already under way on another goroutine may still overlap.
- What the layers hold for the layers above counts against MaxInboundBuffered with the socket's own buffer: a stack whose layers hold the limit pulls nothing more from below until a read above makes room. A packet connection keeps no buffer to hold and is never paced: its PacketLayer carries whatever backpressure its protocol provides.
- Layers carry streams. A packet connection — UDP, IP, unixgram, unixpacket — takes a PacketLayer at the bottom of the chain, which reads its datagrams and hands the layers above the stream it makes of them; a chain without one is refused with ErrLayersNeedStream.
- Every connection ends once, top down: the Handler's OnClose first, if it opened, then every layer's. A connection whose stack never opened — a failed handshake — ends without a Handler callback, and a dial reports its cause instead.
- The end of a stream travels up: a layer whose peer ended its stream calls Upper().End, and the layer above reads io.EOF once it has read the rest.
var PassThroughLayer Layer = LayerFunc(func(LayerContext) LayerHandler { return passThroughHandler{} })
PassThroughLayer is the layer that changes nothing: a WithLayers override that names no layers runs it, so a stack always has a layer. Its handler passes CloseWrite down as well, so a stack of it is transparent throughout — which embedding PassThrough does not grant (see PassThrough).
type LayerCloser ¶ added in v1.9.0
type LayerCloser interface {
OnClosing(ctx LayerContext, cause error)
}
LayerCloser is implemented by a LayerHandler with a protocol close frame to send — a TLS close_notify, a WebSocket Close — when the layer above or this layer closes the connection. OnClosing runs on a turn before the close passes to the layer below, with the close's cause: nil or io.EOF for a graceful close, or a non-nil error for an abort.
A graceful close of a layered connection lets what was queued leave first, the layers' close frames included: the socket's queue drains, bounded by LingerTimeout without progress, before the connection releases — the socket's own Close carries it, and leftover output reaches OnClose as UnflushedError. Nothing reaches the layers or the Handler meanwhile, and what arrives is discarded. An abort closes at once after the walk. A layer that closes the connection itself, through LayerContext.Close or Abort, ends it for the layers above too: what they hold is dropped, and its own OnClosing runs on a turn, never inside the callback that asked.
type LayerContext ¶ added in v1.8.0
type LayerContext interface {
// Lower is the connection below: the socket for the first layer installed,
// or the connection the layer below built for the others. Its inbound
// methods — Peek, PeekChunk, Discard, Read — run in OnRead and OnTimer;
// its writes, deadlines, and addressing may be called at any time. Use
// [SocketOf] to access OS-level socket options on the underlying socket.
Lower() Lower
// Upper is the inbound delivery target above this layer: write decoded
// bytes to it or mark its stream ended.
Upper() Upper
// Open opens the layers above once this layer's negotiation settled — or
// at once from OnOpen when it has none. A dial returns once the top layer
// opened. Call it on the connection's turn.
Open()
// Close ends the connection from this layer, gracefully: writes are
// refused at once, and on the connection's next turn this layer's
// OnClosing runs first, with nil cause, then the layers below run theirs,
// and the socket drains what was accepted before it closes. Neither this
// call nor the turn calls back into the callback that asked. Nothing above
// this layer is called again. A Close while another close is under way
// yields to it and returns nil; once the connection has closed it reports
// net.ErrClosed.
Close() error
// Abort ends the connection at once from this layer: OnClosing hooks are
// told the cause on the next turn, nothing is drained, what the layers
// above hold is dropped, and the socket closes immediately (cutting any
// graceful drain short at once).
Abort(cause error) error
// SetTimer arms this layer's own one-shot timer for when; a zero time
// cancels it.
SetTimer(when time.Time) error
// SetTimerInterval arms this layer's own repeating timer every interval; a
// zero or negative interval cancels it.
SetTimerInterval(interval time.Duration) error
// Wake schedules a turn of the connection.
Wake() error
}
LayerContext is a layer's handle on its place in one connection's stack: Lower is the connection below (toward the wire), Upper is the layer above's inbound delivery buffer (toward the Handler), and Open/Close/Abort/SetTimer control this layer's lifecycle and scheduling.
type LayerFunc ¶ added in v1.8.0
type LayerFunc func(ctx LayerContext) LayerHandler
LayerFunc is a layer written as the function its Attach runs.
func (LayerFunc) Attach ¶ added in v1.8.0
func (f LayerFunc) Attach(ctx LayerContext) LayerHandler
Attach calls f.
type LayerHandler ¶ added in v1.8.0
type LayerHandler interface {
// OnOpen runs once the layers below opened: the place to start a
// handshake. The layers above open when ctx.Open is called, here
// or on a later turn; a layer that negotiates nothing calls it here.
OnOpen(ctx LayerContext)
// OnRead runs on a turn once the layer opened: bytes from below may
// have arrived, or none. It reads them from Lower(), consumes
// them with Discard, and hands up what they became with
// Upper().Write. It may take one chunk at a time: while it consumes
// and bytes still wait below, the turn calls it again. The bottom layer is
// not called at all while the stack holds MaxInboundBuffered unread, until
// a read above makes room; the layers above it go on moving what the stack
// already holds up. A layer whose own delivery to the layer above is full
// waits the same way — its next call is the turn the layer above reads on.
OnRead(ctx LayerContext) error
// OnWrite runs for what the layer above writes, on the writer's
// goroutine and possibly beside other writers: it transforms p, writes
// the result with Lower().Write, and reports how much of p it took.
// p is the writer's again once it returns; one call carries one write
// whole, a Writev's segments joined. What it writes below is never
// refused for the queue's size: the Handler's writes are checked against
// MaxOutboundBuffered before they enter the stack. A layer that holds
// output of its own — a send window — may refuse a write with
// ErrOutboundOverflow, taking none of it. It runs only once the layer
// opened the layers above.
OnWrite(ctx LayerContext, p []byte) (int, error)
// OnTimer runs on the turn the layer's timer came due, before OnRead.
OnTimer(ctx LayerContext) error
// OnClose runs once, as the connection ends, whichever end closed it.
OnClose(ctx LayerContext, cause error)
}
LayerHandler is a layer's instance on one connection: the callbacks UIO runs as the connection's bytes and events pass through the layer.
func LayerOf ¶ added in v1.8.0
func LayerOf(conn Lower) LayerHandler
LayerOf returns the LayerHandler of the layer that built conn — the connection a layer hands up — so the layer above can ask it what it negotiated, a TLS layer's connection state:
if tls, ok := uio.LayerOf(conn).(interface{ State() tls.ConnectionState }); ok { … }
It returns nil for a connection no layer built. FindLayer looks further down.
type ListenOption ¶ added in v1.8.0
type ListenOption interface {
// contains filtered or unexported methods
}
ListenOption configures one listener; see Listen.
type Listener ¶ added in v1.8.0
type Listener interface {
// Addr is the address the listener is bound to; with a port of zero, the
// port the system chose.
Addr() net.Addr
// Close stops accepting on the address and frees it: once Close returns,
// the address can be bound again. Stream connections already accepted
// stay open. A UDP listener's peers share its socket, so they close with
// it, with net.ErrClosed. Two cases free a UDP address only after Close
// returns: a Close from a callback of one of the listener's own peers or
// from inside a Control on its socket frees it once that returns, and a
// Control still running elsewhere holds it until it returns. Closing again
// does nothing.
Close() error
}
Listener is an address an Events accepts on, added while it serves by Listen.
type Lower ¶ added in v1.9.0
type Lower interface {
ReadController
io.Reader
io.Writer
io.ByteWriter
io.StringWriter
// LocalAddr is the connection's local socket address.
LocalAddr() net.Addr
// RemoteAddr is the connection's remote address.
RemoteAddr() net.Addr
// Userdata returns user-defined connection data. It may be read from any
// callback, OnBytesWritten included, and from other goroutines.
Userdata() any
// SetUserdata replaces user-defined connection data, from any goroutine.
SetUserdata(value any)
// SetDeadline sets deadline for both read and write.
// If it is time.Zero, SetDeadline will clear the deadlines.
SetDeadline(t time.Time) error
// SetReadDeadline sets the deadline for future Read calls.
// When the user doesn't update the deadline and the deadline exceeds,
// the connection will be closed.
// If it is time.Zero, SetReadDeadline will clear the deadline.
SetReadDeadline(t time.Time) error
// SetWriteDeadline sets the deadline for future data writing; a deadline
// that passes closes the connection, as SetReadDeadline's does, whether
// or not a write is in flight: a callback cannot be interrupted, so the
// bound is the connection's on every backend.
// If it is time.Zero, SetWriteDeadline will clear the deadline.
SetWriteDeadline(t time.Time) error
// Peek returns the next len(b) bytes without advancing the inbound buffer.
//
// Peek, PeekChunk, Discard, InboundBuffered, Read, WriteTo and the slices
// they return read the connection's inbound buffer: call them only from
// inside the current invocation of this connection's OnOpen, OnRead,
// OnTimer, OnBytesRead or OnClose callback — never from OnBytesWritten, never from
// another goroutine, and never after the callback returned. The slices are
// borrowed from the buffer, and any call that consumes inbound data —
// Read, WriteTo, Discard — or the callback's return may invalidate them
// as the consumed blocks go back to the pool: copy anything that must
// outlive that.
Peek(b []byte) []byte
// PeekChunk returns the first contiguous inbound chunk without advancing it.
// The returned slice is borrowed: Read, WriteTo, Discard or the callback's
// return may invalidate it. See Peek for the calling scope.
PeekChunk() []byte
// Discard advances the inbound buffer with next n bytes, returning the number of bytes discarded.
// See Peek for the calling scope.
Discard(n int) (int, error)
// InboundBuffered returns inbound buffer data length.
// See Peek for the calling scope.
InboundBuffered() int
// ReserveInbound makes the next n inbound bytes, such as a
// length-prefixed packet whose header has arrived, readable as one chunk:
// the bytes buffered so far, up to n, move into one block with room for
// n, and PeekChunk returns them. Bytes read later are borrowed again until
// the next call moves them in too, so a codec calls it in each callback
// while the unit is incomplete and once more when it is complete, and then
// decodes PeekChunk in place instead of copying the unit out with Peek;
// each call copies only what arrived since the last. It does nothing when
// the first chunk already holds n bytes. The block is allocated by the
// first call, so a caller should reserve only a length it has checked,
// and may wait until part of the unit has arrived; with a
// MaxInboundBuffered limit, an n above it returns ErrInboundOverflow. It
// invalidates slices returned by Peek and PeekChunk, and is a no-op for
// datagram connections. See Peek for the calling scope.
ReserveInbound(n int) error
// OutboundBuffered returns payload bytes accepted by this connection but not
// yet written to the socket.
OutboundBuffered() int
// Writev "writev"-like batch write. On a stream connection the buffers
// form one byte stream, written together. On a packet connection each
// buffer is one datagram of its own, sent in one sendmmsg where the
// system has it; the count reports the bytes of the datagrams the socket
// took, and a datagram it refused is lost — a datagram transport leaves
// the retransmission to its protocol above, or has none. Empty buffers
// carry no datagram.
// Notice: non-blocking interface, should not be used as you use std.
Writev(vec [][]byte) (int, error)
// WriteOwned submits buffer without copying and consumes its ownership on
// every return path except ErrOutboundOverflow, which accepts nothing and
// returns the buffer to the caller to resubmit or release. A direct write
// that partially reached the socket and then could not queue its suffix
// reports io.ErrShortWrite instead: that buffer is consumed and the stream
// is being closed, so the partial frame is never resubmitted. For UDP, one
// buffer is sent as one datagram.
WriteOwned(buffer *Buffer) (int, error)
// Flush schedules buffered data for writing without waiting for socket I/O.
// Writes accepted before Flush remain ordered before later writes. When
// another sender is sending the connection's output, Flush leaves the
// bytes to it and returns.
Flush() error
// Wake schedules one OnRead callback after previously submitted tasks: a
// callback that left input unconsumed — its destination was full, say —
// gets the next one from it once it can go on. While read is paused
// the turn runs no OnRead, only timers and layer work; Wake never clears
// a pause.
Wake() error
// SetWakeDeadline schedules one OnTimer callback for the connection at
// when, within one scheduler tick of it: the timed form of Wake. The
// timer turn runs OnTimer and then OnRead, which may find bytes already
// buffered. Due is computed against the clock, so a wake or a read that
// arrives first runs the timer just the same, once. A connection whose
// reads are held (see MaxInboundBuffered) runs the turn anyway —
// consuming what it holds is what a held connection's wake is for — and
// its socket reads resume once the callback consumes below the limit. A
// zero time cancels the pending timer, and arming again replaces
// whatever was armed. Safe from any goroutine.
SetWakeDeadline(when time.Time) error
// SetWakeInterval schedules OnTimer callbacks for the connection every
// interval, the repeating form of SetWakeDeadline, until cancelled by a
// zero or negative interval or replaced by either setter. The native
// scheduler coarsens time into slots of a few milliseconds; an interval
// below a slot still fires — at the retry granularity, about a
// millisecond — and one above a slot fires within a slot of its period.
// A connection needing several timers arms this one at the earliest
// deadline and decides in the callback, by its own clocks, which of them
// came due.
SetWakeInterval(interval time.Duration) error
// CloseWrite shuts the connection's writing half: the peer reads the end
// of the stream once everything accepted before the call has been sent,
// and writes after it return net.ErrClosed. The connection keeps reading
// until the peer shuts its own writing half; with Events.AllowHalfOpen it
// then closes, without it the end of the stream closes it as before. It
// may be called from any goroutine, and calling it again does nothing. On
// a layered connection the top layer's own CloseWrite runs once what was
// written before it has gone below and the layer holds nothing — before
// this returns when that already holds — and for TLS writing a
// close_notify, so it may wait on I/O; otherwise the end is passed on a
// turn. A stack whose layers do not implement CloseWriter returns
// ErrUnsupported. Datagram connections, and stdio-backend connections
// whose net.Conn cannot shut one half, return an unsupported error too.
CloseWrite() error
// State reports where the connection's streams stand: the peer's end
// once everything it sent was read, this end's writing half, and a close.
// It reads state the turns keep, so call it on the connection's turn.
State() ConnState
}
Lower is the connection below a protocol Layer: Conn without whole-connection close verbs, because a layer closes the stack through LayerContext.Close or LayerContext.Abort. CloseWrite remains available to end one direction.
type OutboundHolder ¶ added in v1.8.0
type OutboundHolder interface {
OutboundHeld(ctx LayerContext) int
}
OutboundHolder is implemented by a LayerHandler that cannot always write below at once — a send window waiting for its peer, a compressor gathering a block, a gate holding bytes back — and answers for the bytes it took and still holds: OutboundHeld reports how many. They count in the OutboundBuffered of the connection above it, in the MaxOutboundBuffered check, and in what CloseWrite sends before the end: a byte counts until its write below has returned. OutboundHeld runs on writers' goroutines and beside the turns, so it must not wait on a lock the layer holds while it writes below. A holder that sends what it held outside the turns — a send window opening on a goroutine of its own — calls LayerContext.Wake once the write returns, so what waits for the bytes to leave sees them gone.
type PacketLayer ¶ added in v1.8.0
type PacketLayer interface {
Layer
// CarriesPackets marks the layer as one that reads datagrams from below.
CarriesPackets()
}
PacketLayer is a Layer that takes packets: installed at the bottom of a chain on a packet connection — UDP, IP, unixgram, unixpacket — it reads the connection's datagrams and hands the layers above the stream it makes of them, a reliable stream for a protocol like KCP that runs over one. A chain on a packet connection must start with a PacketLayer; without one the endpoint reports ErrLayersNeedStream. On a stream connection the marker changes nothing.
The framework hands a PacketLayer one datagram per turn: its Lower()'s PeekChunk and Discard see that datagram alone, and what the layer leaves of it when OnRead returns is dropped — a packet connection keeps no unread bytes between turns, so the layer must consume what the turn brought.
The framework never paces a PacketLayer, whatever the layer above has yet to read: a datagram it does not take is gone, so it is called for every one that arrives. The layer bounds what it delivers up itself, and its protocol carries the backpressure to the peer — a full window, for KCP.
type PacketListener ¶ added in v1.8.0
type PacketListener interface {
Listener
// DialPeer adds a peer connection addressed at raddr, on the listener's
// own socket: what it sends leaves from the listener's address, and the
// datagrams raddr answers with are delivered to it — as they would be
// had raddr spoken first. It is the entry point for hole punching. The
// returned Conn is writable at once, before OnOpen, which runs once in a
// turn of its own and is always followed by OnClose. A peer that spoke
// first already has its connection: it is returned with ErrPeerExists,
// keeping the userdata it opened with. userdata is the new connection's
// initial Userdata. Before any datagram from raddr arrives, a closed
// child is replaced: a peer whose old connection is closing can be dialed
// again.
//
// A listener that carries a layer chain refuses DialPeer with
// ErrUnsupported: the peer's connection is the stack's, which only the
// stack opens, and the Conn returned here would bypass every layer.
DialPeer(raddr netip.AddrPort, userdata any) (Conn, error)
// WriteTo sends one datagram to raddr from the listener's socket, from
// the listener's own address, without a connection. It reports the bytes
// sent, not their arrival.
WriteTo(b []byte, raddr netip.AddrPort) (int, error)
}
PacketListener is the Listener of a packet address. Assert it off the Listener Listen returned: only a packet listener's carries it.
type PassThrough ¶ added in v1.8.0
type PassThrough struct{}
PassThrough is a LayerHandler that changes nothing: it opens at once, delivers what arrives, passes the end of the stream up and writes what is written. Embed it in a layer's LayerHandler to write only what that layer transforms — and mind what it lends: OnOpen opens the layers above at once (override it to negotiate first), and CloseWrite is deliberately not among its methods, so a layer that frames its bytes does not inherit a pass-through half-close it would break; a layer that does pass writes through whole implements CloseWriter itself.
func (PassThrough) OnClose ¶ added in v1.8.0
func (PassThrough) OnClose(LayerContext, error)
OnClose does nothing.
func (PassThrough) OnOpen ¶ added in v1.8.0
func (PassThrough) OnOpen(ctx LayerContext)
OnOpen opens the layers above at once.
func (PassThrough) OnRead ¶ added in v1.8.0
func (PassThrough) OnRead(ctx LayerContext) error
OnRead delivers what arrived as it is, and the end of the stream after it.
func (PassThrough) OnTimer ¶ added in v1.8.0
func (PassThrough) OnTimer(LayerContext) error
OnTimer does nothing.
func (PassThrough) OnWrite ¶ added in v1.8.0
func (PassThrough) OnWrite(ctx LayerContext, p []byte) (int, error)
OnWrite writes what is written as it is.
type ReadController ¶ added in v1.9.0
type ReadController interface {
// PauseRead pauses input delivery. It is the application's one switch:
// idempotent, not reference counted. Protocol layers and helpers such as
// Bridge hold pauses of their own, which this switch neither sets nor
// clears.
PauseRead() error
// ResumeRead releases the application's pause. Once no pause remains, a
// turn hands the retained input to OnRead and reading resumes. Without a
// pause to release it does nothing; to get another OnRead for input a
// callback left unconsumed, call Wake.
ResumeRead() error
// ReadPaused reports whether any pause, the application's or another
// owner's, holds the connection's input. A full inbound buffer is not a
// pause: its consumer must still be able to drain it.
ReadPaused() bool
}
ReadController pauses the delivery of one connection's input.
While read is paused the connection's OnRead does not run; OnTimer, writes and close work go on. Input already received is kept and handed to the first OnRead after ResumeRead, before the end of the stream is reported or the connection closes for it. A plain stream stops reading its socket too, so TCP flow control slows the peer at once; a layered stack reads on until its inbound bounds are reached. Pausing does not interrupt a callback or a socket read already in flight: a protocol handling several messages in one callback checks ReadPaused between them.
A fatal transport error, a reset or a local close still ends a paused connection — on the portable stdio backend a reset behind a pause is seen once reading resumes or a read deadline passes, the socket not being read meanwhile. Datagram connections report ErrUnsupported: their peers share one socket. All methods are safe from any goroutine, callbacks included.
type ServeHooks ¶ added in v1.8.0
type ServeHooks interface {
// OnStart runs synchronously after initialization and before listeners
// begin accepting connections.
OnStart(ev *Events)
// OnStop runs once after Serve has stopped its loops and connection tasks.
OnStop(ev *Events)
}
ServeHooks, set as Events.Hooks, runs code around Serve.
type SharedBuffer ¶ added in v1.9.0
type SharedBuffer = bytebuf.SharedBuffer
SharedBuffer holds an immutable, read-only byte payload that can be sent to many connections via WriteShared or BlockingWriter.WriteShared without copying payload bytes or allocating per connection. Call [SharedBuffer.Release] once the broadcast loop finishes; the underlying pooled storage returns to the pool automatically after all in-flight connection sends complete.
func FreezeBuffer ¶ added in v1.9.0
func FreezeBuffer(buffer *Buffer) *SharedBuffer
FreezeBuffer seals buffer into an immutable SharedBuffer and clears *buffer in place so subsequent mutations or ReleaseBuffer calls on buffer cannot affect the frozen broadcast payload.
func NewSharedBuffer ¶ added in v1.9.0
func NewSharedBuffer(p []byte) *SharedBuffer
NewSharedBuffer copies p once into a pooled Buffer and freezes it into an immutable SharedBuffer. The caller may freely mutate or reuse p afterward.
type SocketConn ¶ added in v1.9.0
type SocketConn interface {
// SetLinger sets the behavior of Close on a connection which still
// has data waiting to be sent or to be acknowledged.
//
// If sec < 0 (the default), the operating system finishes sending the
// data in the background.
//
// If sec == 0, the operating system discards any unsent or
// unacknowledged data.
//
// If sec > 0, the data is sent in the background as with sec < 0. On
// some operating systems after sec seconds have elapsed any remaining
// unsent data may be discarded.
SetLinger(secs int) error
// SetNoDelay controls whether the operating system should delay
// packet transmission in hopes of sending fewer packets (Nagle's
// algorithm).
// The default is true (no delay), meaning that data is sent as soon as possible after a Write.
SetNoDelay(nodelay bool) error
// SetKeepAlive sets whether the operating system should send
// keep-alive messages on the connection.
SetKeepAlive(keepalive bool) error
// SetKeepAlivePeriod tells operating system to send keep-alive messages on the connection
// and sets period between TCP keep-alive probes.
SetKeepAlivePeriod(secs int) error
// Control runs fn with the connection's descriptor, for the socket
// options the dedicated setters do not carry — IP_TTL for a NAT probe,
// IP_TOS, SO_MARK. It returns after fn, and net.ErrClosed once the
// connection's close was requested. A datagram connection shares its
// descriptor with its listener and peers, so what it sets lands on the
// shared socket, which outlives one peer's close. The descriptor is valid
// only during fn; native external calls may use a temporary duplicate.
// fn must not wait for what its own connection has to make happen: a
// callback, a Dial's registration, OnClose after a close — the descriptor
// reference Control holds, and on stdio the loop it may run in, can be
// part of what fn is waiting for.
Control(fn func(fd uintptr)) error
// SetReadBuffer sets the size of the operating system's
// receive buffer associated with the connection.
SetReadBuffer(size int) error
// SetWriteBuffer sets the size of the operating system's
// transmit buffer associated with the connection.
SetWriteBuffer(size int) error
}
SocketConn exposes OS-level socket options and raw descriptor control for connections backed by a physical socket. Use SocketOf to reach it through protocol layers or connection wrappers; virtual streams such as multiplexed streams report false.
func SocketOf ¶ added in v1.9.0
func SocketOf(c Lower) (SocketConn, bool)
SocketOf returns the underlying SocketConn of c, unwrapping protocol layers and Unwrapper decorators. It returns (nil, false) for virtual connections that have no dedicated OS socket, such as multiplexed streams.
type SocketControl ¶ added in v1.8.0
SocketControl runs on a socket's descriptor, for the options the dedicated setters do not carry: IP_TTL for a NAT probe, IP_TOS, SO_MARK, or an option a hole punch needs before its socket connects or binds. network and address are what the socket is for; fd is valid only for the call.
type Stats ¶ added in v1.9.0
type Stats struct {
// Pollers is the number of active event loops (0 before Serve starts).
Pollers int
// ActiveConnections is the number of currently open connections (stream
// connections and active UDP peer connections).
ActiveConnections int64
// TotalConnections counts connections that have opened since Serve started.
TotalConnections uint64
// TurnQueue is the number of connection turns currently queued in UIO's
// owned scheduler (0 on the stdio backend or with a custom Executor).
TurnQueue int64
// WriteQueue is the number of background write turns currently queued in
// UIO's owned scheduler.
WriteQueue int64
// ActiveTurnShards is the active shard count of UIO's owned turn scheduler.
ActiveTurnShards int
// RunningWorkers is the number of owned scheduler workers currently
// executing connection or write turns.
RunningWorkers int
// IdleWorkers is the number of parked owned scheduler workers ready to
// serve turns without spawning a goroutine.
IdleWorkers int
// OutboundOverflows counts writes rejected with ErrOutboundOverflow.
OutboundOverflows uint64
}
Stats is a point-in-time, zero-allocation runtime snapshot of an Events instance. All fields are read lock-free from per-loop and per-shard counters, adding zero allocations and zero data-path contention.
type TrafficObserver ¶ added in v1.8.0
type TrafficObserver interface {
// OnBytesRead reports bytes read from the socket before OnRead and
// shares its inbound-access scope.
OnBytesRead(c Conn, n int)
// OnBytesWritten reports bytes successfully written to the socket. It may
// run on a backend writer goroutine or a native write turn, concurrently
// with the connection's other callbacks, and does not grant inbound-buffer
// access. The final flush of a closing native connection reports from the
// goroutine that releases it, which during shutdown is the one returning
// from Serve. Calls for one connection never overlap each other: on the
// native backend a Write made inside OnBytesWritten is queued and sent
// after it returns. A UDP connection's datagrams leave on the goroutines
// that write them, and OnBytesWritten may report several of them, on any
// one of those goroutines, after its send. With layers installed it may run
// inside a layer's write below, so it must not write to or close the
// connection.
OnBytesWritten(c Conn, n int)
}
TrafficObserver, set as Events.Observer, is told the bytes each connection reads and writes. Both callbacks are observation only: they report I/O that just happened. They are named for the bytes they count: OnRead and OnWrite name the data path's callbacks — LayerHandler.OnRead and OnWrite, and the Handler's OnRead — not its byte totals, which is why the counts here carry Bytes in their names.
type UnflushedError ¶ added in v1.1.0
type UnflushedError struct {
Remaining int64
}
UnflushedError reports payload accepted by the framework but not sent before the connection was closed.
func (UnflushedError) Error ¶ added in v1.1.0
func (err UnflushedError) Error() string
func (UnflushedError) Unwrap ¶ added in v1.1.0
func (err UnflushedError) Unwrap() error
type Unwrapper ¶ added in v1.9.0
type Unwrapper interface {
Unwrap() Conn
}
Unwrapper is implemented by connection decorators and protocol-layer nodes so SocketOf, FindLayer, LayerOf, and flow-control helpers can reach the underlying connection.
type Upper ¶ added in v1.9.0
type Upper interface {
io.Writer
// End tells the layer above the stream ended: once it read what was
// written, its Read reports io.EOF. A layer calls it when its peer ended
// its stream — the socket's end, a TLS close_notify. At the top of the
// stack, an Events without AllowHalfOpen closes the connection with
// io.EOF once the Handler's OnRead has run; with it, the Handler may go on
// writing and end its own half with CloseWrite. The stack ends without it
// too, once the socket ended and the layers handed up everything they
// could — an input no layer could complete ends the stream as a
// truncation (io.ErrUnexpectedEOF) instead. Call it in OnRead or
// OnTimer.
End()
// Reserve returns at least n bytes of room past what is written, for the
// layer to fill in place — decrypting straight into it — and Commit
// delivers the first n of them. Between the two, write nothing else to
// Upper: Write appends where Reserve's room begins. Call both in OnRead or
// OnTimer.
Reserve(n int) []byte
Commit(n int)
// Buffered reports how many delivered bytes the layer above has not read.
Buffered() int
// Yield tells UIO the layer stopped short of what it could deliver — its
// bound was reached, with bytes waiting below or in its own buffers — so
// the next read above schedules a turn to take the rest.
Yield()
}
Upper is the inbound delivery buffer feeding the layer (or Handler) above. Write always takes all of p and never fails. The framework paces the layer, not its writes: once a layer's delivery reaches DefaultDeliverBound — Events.MaxInboundBuffered, when set — the framework stops calling that layer's OnRead until the layer above reads. What one write adds is not capped: the write that crosses the bound, and any made from OnOpen, takes the delivery past it by that write's size. Its methods run on the connection's turn — in OnOpen, OnRead or OnTimer.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
module
|
|
|
internal
|
|
|
blockio
Package blockio implements symmetric bounded blocking Reader and Writer endpoints backed by non-blocking connection turns.
|
Package blockio implements symmetric bounded blocking Reader and Writer endpoints backed by non-blocking connection turns. |
|
bytebuf
Package bytebuf provides pooled contiguous and segmented byte buffers with explicit ownership transfer.
|
Package bytebuf provides pooled contiguous and segmented byte buffers with explicit ownership transfer. |
|
fdmap
Package fdmap maps OS descriptors to connection objects using the cheapest synchronization available on each platform.
|
Package fdmap maps OS descriptors to connection objects using the cheapest synchronization available on each platform. |
|
plocal
Package plocal keeps one value per P in front of a sync.Pool: the P-level counterpart of thread-local storage, for objects a goroutine borrows and returns within a short stretch of work, such as a buffer for one read.
|
Package plocal keeps one value per P in front of a sync.Pool: the P-level counterpart of thread-local storage, for objects a goroutine borrows and returns within a short stretch of work, such as a buffer for one read. |
|
poller
Package poller normalizes epoll and kqueue readiness semantics on Unix.
|
Package poller normalizes epoll and kqueue readiness semantics on Unix. |
|
pool
Package pool implements bounded power-of-two object size classes.
|
Package pool implements bounded power-of-two object size classes. |
|
readcontrol
Package readcontrol shares input-consumer ownership between the transport and the protocol packages without exposing owner handles in the public API.
|
Package readcontrol shares input-consumer ownership between the transport and the protocol packages without exposing owner handles in the public API. |
|
shardpool
Package shardpool runs tasks on a pool of workers grouped in shards, with every task queued on the shard its key picks.
|
Package shardpool runs tasks on a pool of workers grouped in shards, with every task queued on the shard its key picks. |
|
socket
Package socket contains platform-specific descriptor and socket operations used by UIO's native transports.
|
Package socket contains platform-specific descriptor and socket operations used by UIO's native transports. |
|
taskqueue
Package taskqueue provides a small intrusive MPSC FIFO queue.
|
Package taskqueue provides a small intrusive MPSC FIFO queue. |
|
timewheel
Package timewheel is a hashed timing wheel of deadlines, one instance per event loop, holding the wake timers of that loop's connections.
|
Package timewheel is a hashed timing wheel of deadlines, one instance per event loop, holding the wake timers of that loop's connections. |
|
writecontrol
Package writecontrol shares outbound-progress notifications between the transport and protocol packages without adding public factory methods.
|
Package writecontrol shares outbound-progress notifications between the transport and protocol packages without adding public factory methods. |
|
Package ubridge relays bidirectional stream connections with end-to-end backpressure, half-close propagation, and abort forwarding.
|
Package ubridge relays bidirectional stream connections with end-to-end backpressure, half-close propagation, and abort forwarding. |
|
Package ukcp runs KCP — a reliable, ordered byte stream over an unreliable datagram transport — as a UIO layer, with the protocol engine vendored from github.com/xtaci/kcp-go (see internal/kcp).
|
Package ukcp runs KCP — a reliable, ordered byte stream over an unreliable datagram transport — as a UIO layer, with the protocol engine vendored from github.com/xtaci/kcp-go (see internal/kcp). |
|
internal/kcp
if build tag debug is not set, debugLog is a no-op eliminated at compile time
|
if build tag debug is not set, debugLog is a no-op eliminated at compile time |
|
Package umux multiplexes bidirectional byte streams over one uio.Conn.
|
Package umux multiplexes bidirectional byte streams over one uio.Conn. |
|
Package utls runs TLS as a protocol layer over a UIO transport, with crypto/tls doing the cryptography.
|
Package utls runs TLS as a protocol layer over a UIO transport, with crypto/tls doing the cryptography. |
|
Package uws provides an asynchronous WebSocket server and client built on UIO.
|
Package uws provides an asynchronous WebSocket server and client built on UIO. |
|
autobahn/server
command
|
|
|
examples/echo
command
|
|
|
examples/nethttp
command
|
|
|
internal/compress
Package compress implements RFC 7692 message DEFLATE with bounded output and negotiated context takeover.
|
Package compress implements RFC 7692 message DEFLATE with bounded output and negotiated context takeover. |
|
internal/extension
Package extension parses and negotiates WebSocket extension headers.
|
Package extension parses and negotiates WebSocket extension headers. |
|
internal/frame
Package frame implements the wire-level WebSocket frame codec.
|
Package frame implements the wire-level WebSocket frame codec. |
|
internal/handshake
Package handshake parses, validates, and builds RFC 6455 HTTP upgrades.
|
Package handshake parses, validates, and builds RFC 6455 HTTP upgrades. |