uio

package module
v1.7.0 Latest Latest
Warning

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

Go to latest
Published: Oct 17, 2026 License: Apache-2.0 Imports: 25 Imported by: 2 modules, 2 packages

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

UIO - Ultra Fast I/O Framework for Go

GoDoc license-Apache 2

UIO (pronounced "ultra-IO") is a high-performance, event-driven networking framework for Go, designed for building scalable and efficient TCP/UDP servers and clients. It leverages modern I/O multiplexing techniques and provides a lightweight, non-blocking API for low-latency applications.

Features

  • 🚀 Event-Driven Architecture: Built on epoll/kqueue (Unix-like) for optimal I/O scheduling and stdio for others platform (Windows).
  • 🌐 Cross-Platform: Supports Linux, macOS, BSD variants, and Windows.
  • 🔄 Protocol Support: TCP, TCP4/TCP6, UDP, UDP4/UDP6, Unix domain sockets.
  • ⚡ Zero-Copy Optimizations: Batched read/write operations minimize memory copies.
  • 🧩 Flexible Event Hooks: OnOpen, OnData, OnClose callbacks for connection lifecycle management.
  • 🔧 Tunable Parameters:
    • Custom buffer sizes
    • Write buffering thresholds
    • Per-connection inbound/outbound limits
    • SO_REUSEPORT support

Installation

go get github.com/urpc/uio

Overview


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 and hand runnable connections to the Executor. The default is
	// one loop per four Ps, between one and eight, capped by
	// runtime.GOMAXPROCS(0).
	Pollers int

	// Executor optionally supplies an asynchronous native connection-task
	// scheduler with typed single and batch submission.
	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

	// MaxBufferSize is the buffer size of each socket read. The default is 4 KiB.
	MaxBufferSize int

	// WriteBufferedThreshold batches smaller native callback writes until the
	// connection task flushes. Zero disables size-based buffering.
	WriteBufferedThreshold int

	// MaxOutboundBuffered limits accepted but unsent payload bytes per
	// connection. Native transports pause that connection's reads while its
	// backlog is high. Zero disables the limit.
	MaxOutboundBuffered int

	// MaxInboundBuffered limits payload left unread after a callback returns.
	// Zero disables the limit.
	MaxInboundBuffered int

	// Lifecycle and data callbacks are serialized per connection; different
	// connections may execute concurrently.
	OnOpen func(c Conn)

	// OnData runs while inbound access methods are valid.
	OnData func(c Conn) error

	// OnClose is final and never overlaps OnOpen or OnData for its connection;
	// only a connection that got OnOpen gets it.
	OnClose func(c Conn, err error)

	// OnInbound runs before OnData and shares its inbound-access scope.
	OnInbound func(c Conn, readBytes int)

	// OnOutbound 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.
	OnOutbound func(c Conn, writeBytes int)

	// OnStart it triggers on the server initialized.
	OnStart func(ev *Events)

	// OnStop it triggers on the server closed.
	OnStop func(ev *Events)
}

Quick Start

Basic Echo Server

On native Unix, a connection is owned by its turn: one serialized task on the configured Executor or UIO's own connection scheduler runs all of the connection's callbacks, reads its socket, and also releases the connection once it is closing. The event loops only collect readiness. Each loop is one epoll or kqueue instance; stream listeners, connections and UDP sockets are spread over the loops in turn, whatever their descriptor numbers, and the loop's waiters accept on its listeners, register what they accept, and hand runnable connections to the scheduler, without ever running a callback or waiting for a connection. One blocked connection therefore blocks neither a loop nor another connection. Several loops keep a connection's events within one cluster of cores. By default, from 8 to 63 Ps each loop has one waiter, which parks in the Go runtime's netpoller while its loop is busy and blocks in the kernel once the loop goes quiet; below 8 Ps the waiters always park (two on the one loop from 2 Ps up), and a host that runs more than eight waiters blocks them all.

A stream connection's first turn runs OnOpen, then reads whatever the peer already sent and runs OnData for it in the same turn. Registration stays with the waiters, not the turns: the kernel serializes registrations per epoll or kqueue instance, and a few waiters per loop contend for it far less than every worker would. A connection that closes in a callback is released when that callback returns, and OnClose is delivered in the same turn. A close requested from another goroutine, a deadline, or shutdown marks the connection and schedules its turn, which releases it the same way. Socket options and deadlines set from other goroutines apply on the caller's goroutine.

Output a connection's own callbacks write leaves when the read round ends, or once it fills a coalescing block. Output written from other goroutines, such as replies an RPC handler finishes after its request's callback returned, is sent by a write turn: a short task that only moves queued bytes to the socket, so it is not held behind a read round or a slow callback of the same connection. The exception is a turn whose callback reserved outbound bytes with ReserveOutbound, as the uws server does for its replies: it keeps the socket until it ends, as every turn did before write turns. One claim per connection orders all senders, so bytes leave in the order they were accepted; with an Executor, write turns are submitted to it as well; without one they run on a sharded scheduler of their own, beside the one for connection turns.

A UDP listener is a connection of its own whose turns read every peer's datagrams and run the peers' callbacks, since the peers share its socket. A UDP Write or WriteOwned sends its datagram before returning, from any goroutine. The stdio/Windows backend instead uses dedicated blocking read/write goroutines per connection; Executor does not apply there. Without an external executor, native UIO runs connection turns on a sharded taskgo queue, two shards per P (runtime.GOMAXPROCS(0)). All of a connection's turns go to one shard, picked by its loop first and its descriptor second, so the connections of one loop share a subset of the shards and a loop's batch of runnable connections wakes few workers. A worker keeps serving its shard until the shard runs dry, so a connection's turns stay on one CPU, whose caches then hold its socket. Workers that run out of work take over shards still holding tasks, and a shard whose worker is blocked in a callback is handed to another worker after a few milliseconds, so a callback that blocks holds up no other shard and its own only briefly. Workers are added only while callbacks block, up to 512 per P, and idle ones exit after 30 seconds. Write turns run on a sharded scheduler of their own under the same key.

Events.Dial and Events.DialContext perform synchronous resolution and connection setup, and register the new connection on the calling goroutine. Native callbacks run on task workers and may dial, but the synchronous operation occupies that worker; move long dials to an application goroutine when appropriate. A synchronous dial similarly blocks a stdio connection's callback path. On the stdio backend, a call from an event-loop goroutine returns ErrDialOnEventLoop. Use DialContext when the operation needs cancellation or a deadline. Events.Serve listens on every supplied address. Call Serve() without an address when using an Events instance only for outbound dialing.

Events.Close only publishes shutdown and always returns without waiting. The return of Serve is the usual lifecycle join point; Events.Wait is available when shutdown is initiated from another goroutine. Wait includes event loops, connection tasks, stdio I/O goroutines, and OnStop, and must not be called from one of those callbacks.

Events.Adopt transfers an already-established stream connection into the event loops. The Events instance must already be serving, and ownership is consumed on both success and failure; the caller must never use the original net.Conn again after calling it.

MaxOutboundBuffered is the only outbound backpressure budget. It is applied per connection: a write that would push buffered unsent data beyond it returns ErrOutboundOverflow, and reads are never paused by it — a full-duplex peer can always drain its side. MaxInboundBuffered closes a connection with ErrInboundOverflow when a callback leaves too much input unconsumed. Both limits default to zero, which disables them.

The inbound buffer is callback-scoped. Peek, PeekChunk, Discard, InboundBuffered, ReserveInbound, Read, WriteTo and the slices they return may only be used inside the current invocation of this connection's OnOpen, OnInbound, OnData or OnClose callback — not from OnOutbound and not from another goroutine. PeekChunk (and Peek) may return a borrowed slice, and any call that consumes inbound data — Read, WriteTo, Discard — or the callback's return invalidates it as the consumed blocks go back to the pool, so copy anything processed asynchronously. Race-enabled builds panic on a call outside a callback as a misuse diagnostic; builds without the race detector compile that diagnostic out, and there the contract rests on the documentation and on the connection turn's serialization alone. Cross-goroutine access is per method, not per type: Write and Close are documented safe from other goroutines, the inbound methods are not, and every other method's comment says where it may be called — never assume the whole Conn is goroutine-safe.

A codec that decodes length-prefixed packets in place, from PeekChunk, can keep doing so for a packet that spans many reads with Conn.ReserveInbound. Once the header has given the packet's length, each call moves the bytes buffered so far into one block with room for the whole packet, so a packet that has arrived is one chunk and is decoded without first being copied out with Peek. Call it in every callback while the packet is incomplete and once more when it is complete; each call copies only the bytes read since the last. The block is allocated by the first call, so reserve only lengths the codec has already checked against its limit, and for large ones consider waiting until part of the packet has arrived:

total := 4 + size // header plus payload
if err := conn.ReserveInbound(total); err != nil {
	return err
}
if chunk := conn.PeekChunk(); len(chunk) >= total {
	err := decode(chunk[4:total])
	_, _ = conn.Discard(total)
	return err
}
return errIncomplete // more callbacks follow as the rest arrives

For encoders that can write into caller-provided storage, AcquireBuffer and Conn.WriteOwned avoid copying the encoded result into asynchronous outbound storage. WriteOwned consumes the buffer on both success and failure, with one exception: ErrOutboundOverflow means nothing was accepted, so the buffer remains the caller's to resubmit or release. When a direct write partially reached the socket and the remainder cannot be queued, the error is io.ErrShortWrite instead: that buffer is consumed and the stream is closing, so the partial frame is never resubmitted:

buffer := uio.AcquireBuffer(size)
dst := buffer.AvailableBuffer()[:size]
n, err := encode(dst)
if err != nil {
	uio.ReleaseBuffer(buffer)
	return err
}
buffer.CommitWrite(n)
_, err = conn.WriteOwned(buffer)
if err == uio.ErrOutboundOverflow {
	uio.ReleaseBuffer(buffer)
}
return err

Inside a native stream connection's own callback, Conn.ReserveOutbound goes one step further: it appends the requested bytes to the connection's outbound queue and returns them for the encoder to fill in place, so a round of small replies can share a few pooled blocks and be flushed together after the callback returns. Fill every reserved byte before the callback returns or flushes. Elsewhere, including on the stdio backend, or while output written from another goroutine is queued for or being sent by a write turn, it returns ErrReserveUnsupported and the caller falls back to another write:

dst, err := conn.ReserveOutbound(size)
if errors.Is(err, uio.ErrReserveUnsupported) {
	// not in the connection's callback: encode into a buffer and WriteOwned it
} else if err == nil {
	encode(dst)
}
package main

import (
	"fmt"

	"github.com/urpc/uio"
)

func main() {

	var events uio.Events

	events.OnOpen = func(c uio.Conn) {
		fmt.Println("connection opened:", c.RemoteAddr())
	}

	events.OnData = func(c uio.Conn) error {
		_, err := c.WriteTo(c)
		return err
	}

	events.OnClose = func(c uio.Conn, err error) {
		fmt.Println("connection closed:", c.RemoteAddr())
	}

	if err := events.Serve(":9527"); nil != err {
		fmt.Println("server exited with error:", err)
	}
}

tcpkali2 Benchmark (2026-09-25)

The following results use tcpkali2 0.4.0 on a dual-socket Xeon E5-2690 v3 host with 48 logical CPUs. Server and client CPU resources were isolated with taskset: the server used all 24 logical CPUs in NUMA node 0 (0-11,24-35) and tcpkali2 used all 24 logical CPUs in NUMA node 1 (12-23,36-47). Both events and stdio ran with GOMAXPROCS=24; events additionally used 24 pollers, while tcpkali2 used -w 24. At that revision, Linux events collected stream readiness on a shared data poller, so the pollers handled accept, registration and close rather than stream readiness.

The load used 1,000 loopback connections, a 3-second warmup, a 10-second measurement window, 1 KiB random messages, --pipeline, and the default TCP_NODELAY setting. Each table row is the run with the median request rate from three runs, and the runs of all eight configurations were interleaved. Every run completed with a 100% success rate and zero connection errors. The UWS server had compression disabled. P99 is saturated pipeline latency, not idle single-request latency. UIO revision b23241d (taskgo v1.5.0) was built with Go 1.27.1 on Ubuntu 22.04.5 with Linux 6.8.0.

Plain TCP was run with:

GOMAXPROCS=24 taskset -c 0-11,24-35 ./echo -pollers 24 -buffer 4096

taskset -c 12-23,36-47 tcpkali2 -w 24 -c 1000 \
  --connect-rate 2000 -T 10s --warmup 3s -s 1024 \
  --pipeline 127.0.0.1:9527

./echo is built from examples/bench/echo, with -tags stdio for the stdio backend. Both backends were tested with the default 4 KiB MaxBufferSize and a custom 16 KiB value (-buffer 16384). The UWS server runs the uws/examples/echo handler with the same Pollers and MaxBufferSize settings; the UWS run adds --websocket and targets port 19701.

Service Backend MaxBufferSize Server CPUs Requests/s Avg latency P99 latency Bandwidth Peak RSS
UIO TCP echo events 4 KiB 24 8,902,695 3.53 ms 4.92 ms 18,233 MB/s 12.5 MiB
UIO TCP echo events 16 KiB 24 9,816,081 2.94 ms 5.71 ms 20,103 MB/s 12.5 MiB
UIO TCP echo stdio 4 KiB 24 8,981,015 3.51 ms 10.58 ms 18,393 MB/s 56.6 MiB
UIO TCP echo stdio 16 KiB 24 9,686,031 3.20 ms 9.56 ms 19,837 MB/s 83.4 MiB
UWS echo events 4 KiB 24 5,471,521 4.17 ms 14.38 ms 11,206 MB/s 31.7 MiB
UWS echo events 16 KiB 24 5,435,586 4.21 ms 14.46 ms 11,132 MB/s 32.0 MiB
UWS echo stdio 4 KiB 24 5,369,671 4.33 ms 14.44 ms 10,997 MB/s 76.4 MiB
UWS echo stdio 16 KiB 24 5,364,657 4.28 ms 14.26 ms 10,987 MB/s 108.8 MiB

Bandwidth is aggregate application traffic in both directions. Peak RSS was sampled every 100 ms during the selected median-throughput run. stdio's per-connection read/write goroutines and buffers account for most of its higher memory use and scale with the number of live connections.

Selection guidance
  • MaxBufferSize still helps plain TCP batching. Raising it from 4 KiB to 16 KiB improved TCP echo throughput by about 10% for events and about 8% for stdio. At 4 KiB the two backends are within 1% of each other, and events has less than half of stdio's P99 latency. With both tuned to 16 KiB, events was about 1% faster, had lower average and P99 latency, and used about one seventh of stdio's RSS.
  • For UWS, events is about 2% faster than stdio in this test, with slightly lower average latency, about the same P99, and roughly 60% lower RSS at 4 KiB. Raising MaxBufferSize to 16 KiB did not materially improve either backend for the 1 KiB WebSocket workload, and increased stdio RSS by about 40%, so 4 KiB remains the better choice for this profile.
  • Tune MaxBufferSize against the application protocol and payload. Larger reads reduce syscall and callback overhead for streaming TCP, but they are not a universal throughput improvement.
  • For large numbers of long-lived or mostly idle connections, prefer events: its memory footprint is shared by event loops instead of being proportional to two goroutines and a read buffer per connection.
  • Results remain workload dependent. Pipeline saturation amplifies queueing latency, and placing server and client on separate NUMA nodes adds inter-node loopback traffic. Use the same client version, connection count, payload, Go version, poller/worker counts, CPU placement, and warmup when comparing a deployment.

License

The repository released under version 2.0 of the Apache License.

Documentation

Overview

Package uio provides event-driven connections whose native Unix data path runs in serialized connection tasks outside epoll/kqueue loops.

Index

Constants

This section is empty.

Variables

View Source
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")
	ErrReserveUnsupported = errors.New("uio: outbound reservation needs the connection's own callback")
)
View Source
var ErrUDPWriteOnEventLoop = errors.New("uio: UDP write cannot wait on another event loop")

Deprecated: nothing returns ErrUDPWriteOnEventLoop any more; a UDP write sends its datagram from any goroutine.

Functions

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.

Types

type Buffer added in v1.1.0

type Buffer = bytebuf.Buffer

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

func AcquireBuffer(capacity int) *Buffer

AcquireBuffer returns an empty pooled buffer with at least capacity bytes of writable space. Release it when ownership is not transferred to WriteOwned.

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 {
	// 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 called outside a
	// callback, but callers must serialize it with SetUserdata. Native
	// OnOutbound may run beside the connection's other callbacks.
	Userdata() any

	// SetUserdata replaces user-defined connection data. It may be called outside
	// a callback, but callers must serialize it with Userdata.
	SetUserdata(value any)

	// 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

	// 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

	// 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.
	// 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, OnInbound,
	// OnData or OnClose callback — never from OnOutbound, 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 a 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

	// WriterTo
	// WriteTo drains inbound data; see Peek for the calling scope.
	// Notice: non-blocking interface, should not be used as you use std.
	io.WriterTo

	// ReadWriteCloser
	// Read is inbound access; see Peek for the calling scope. Write and Close
	// are safe from other goroutines.
	// Stream writes are non-blocking; a native UDP write makes one
	// non-blocking send and returns its result.
	io.ReadWriteCloser

	// ByteWriter
	// Notice: non-blocking interface, should not be used as you use std.
	io.ByteWriter

	// StringWriter
	// Notice: non-blocking interface, should not be used as you use std.
	io.StringWriter

	// Writev "writev"-like batch write optimization.
	// 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)

	// ReserveOutbound appends n bytes to the connection's outbound queue and
	// returns them for the caller to fill in place, so an encoder writes
	// straight into the queue instead of into a buffer that is copied again.
	// It works only in a native stream connection's own callback, where the
	// queue is sent after the callback returns; elsewhere, or while output
	// written from another goroutine is queued for or being sent by a write
	// turn, it reserves nothing and returns ErrReserveUnsupported, and the
	// caller writes another way. Once a reservation succeeds, output from other
	// goroutines waits for the end of the connection's turn.
	// Every reserved byte must be written before the callback returns and
	// before the next Flush.
	ReserveOutbound(n int) ([]byte, 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 OnData callback after previously submitted tasks.
	Wake() error

	// YieldRead ends the current read round and schedules remaining buffered or
	// socket data for a later OnData callback. It may only be called from a
	// connection callback.
	YieldRead() error

	// CloseWith requests the close and returns. On native Unix the
	// connection's turn releases it once the callback that closed it has
	// returned, and reports unsent accepted payload as UnflushedError.
	CloseWith(err 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 CloseWith return after the close request is accepted; OnClose is final. Native UDP writes send the datagram before returning, from any goroutine.

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 on a sharded taskgo queue (see
	// taskgo.NewTaskKeyed) and write turns on a sharded scheduler 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

	// MaxBufferSize is the buffer size of each socket read. Native connection
	// tasks may perform multiple reads per readiness event. The default is 4 KiB.
	MaxBufferSize 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.
	MaxOutboundBuffered int

	// MaxInboundBuffered limits payload left unread after a callback returns.
	// Exceeding it closes the connection with ErrInboundOverflow. Zero disables
	// the limit.
	MaxInboundBuffered int

	// OnOpen fires first for every connection, in the connection's first
	// turn. On Unix a stream connection's first turn reads whatever its peer
	// already sent right after OnOpen returns, in the same turn. Lifecycle and
	// data callbacks are serialized per connection, while callbacks for
	// different connections may run concurrently.
	OnOpen func(c Conn)

	// OnData fires when inbound data is available. Inbound access methods are
	// valid only for this callback invocation.
	OnData func(c Conn) error

	// OnClose is the final callback for a connection and never overlaps its
	// OnOpen or OnData 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 func(c Conn, err error)

	// OnInbound reports bytes read from the socket before OnData and shares its
	// inbound-access scope.
	OnInbound func(c Conn, readBytes int)

	// OnOutbound 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 OnOutbound is queued and sent after it returns. A UDP
	// connection's datagrams leave on the goroutines that write them, and
	// OnOutbound may report several of them, on any one of those goroutines,
	// after its send.
	OnOutbound func(c Conn, writeBytes int)

	// OnStart runs synchronously after initialization and before listeners
	// begin accepting connections.
	OnStart func(ev *Events)

	// OnStop runs once after Serve has stopped its loops and connection tasks.
	OnStop func(ev *Events)
	// 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.1.0

func (ev *Events) Adopt(conn net.Conn, userdata any) (Conn, error)

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

func (ev *Events) Close(err error) error

Close publishes shutdown and returns without waiting. Use Wait or the return of Serve as the lifecycle join point.

func (*Events) Dial

func (ev *Events) Dial(addr string, userdata any) (Conn, error)

Dial connects to the address on the named network.

Known networks are "tcp", "tcp4" (IPv4-only), "tcp6" (IPv6-only), "udp", "udp4" (IPv4-only), "udp6" (IPv6-only), "ip", "ip4" (IPv4-only), "ip6" (IPv6-only), "unix", "unixgram" and "unixpacket".

Examples:

Dial("tcp://golang.org:http")
Dial("tcp://192.0.2.1:http")
Dial("tcp://198.51.100.1:80")
Dial("udp://[2001:db8::1]:domain")
Dial("udp://[fe80::1%lo0]:53")
Dial("tcp://:80")
Dial("unix:///path/your/unix.sock")

func (*Events) DialContext added in v1.0.1

func (ev *Events) DialContext(dialCtx context.Context, addr string, userdata any) (Conn, error)

DialContext connects synchronously and allows cancellation while resolving or establishing the connection. The connection is registered on the calling goroutine, so calling it from a connection callback waits for nothing but the dial itself.

func (*Events) Serve

func (ev *Events) Serve(addrs ...string) (err error)

Serve starts the event loops and listens on each supplied address. Calling Serve without an address starts a dial-only Events.

func (*Events) Wait added in v1.4.0

func (ev *Events) Wait() error

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

type Executor interface {
	Submit(task IOTask) bool
	SubmitBatch(tasks []IOTask) int
}

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 OnOutbound for the close's final flush — runs on UIO's own goroutines, a few at a time. A connection whose first turn is refused never got OnOpen, so it closes without OnClose too; a Dial that returned it has handed its caller a closed connection. A native connection may have its connection turn and a write turn in flight at once; both arrive here.

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

Directories

Path Synopsis
examples module
internal
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, kqueue, and blocking-backend wake semantics.
Package poller normalizes epoll, kqueue, and blocking-backend wake semantics.
pool
Package pool implements bounded power-of-two object size classes.
Package pool implements bounded power-of-two object size classes.
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.
uws
Package uws provides an asynchronous WebSocket server built on UIO.
Package uws provides an asynchronous WebSocket server built on UIO.
autobahn/server command
examples/echo 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.

Jump to

Keyboard shortcuts

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