uio

package module
v1.8.0 Latest Latest
Warning

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

Go to latest
Published: Oct 29, 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

Go Reference CI License

uio is an event-driven networking library for Go. You write a few callbacks; uio watches the sockets, runs your code when a connection has something to say, and sends your replies in as few system calls as it can — without a goroutine per connection.

Highlights

  • Callbacks, not goroutines. OnOpen, OnRead, OnTimer and OnClose run in order for each connection and never overlap, so the state they share needs no locks, and on epoll/kqueue an idle connection is a small struct rather than a parked goroutine.
  • A slow handler stalls nothing else. On epoll/kqueue, event loops only collect readiness; callbacks run on a worker pool, and work stuck behind a blocked callback is handed to another worker within milliseconds.
  • Write from anywhere. Write, WriteOwned and Close are safe from any goroutine; bytes leave in the order they were written.
  • Zero-copy where it counts. Decode packets straight from the read buffer, encode replies straight into the send queue, and send a round of replies together, usually in one writev.
  • Built-in backpressure. Per-connection limits on buffered input and output: input past its limit pauses reads, so TCP flow control slows a flooding peer, and output past its limit fails the write instead of growing memory without bound.
  • Cross-platform. epoll on Linux, kqueue on macOS and the BSDs, and a portable goroutine-per-connection backend on Windows (or anywhere with -tags stdio).
  • TCP, UDP and Unix sockets, listening and dialing, IPv4 and IPv6.

Install

go get github.com/urpc/uio

uio needs Go 1.25 or newer.

Quick start

An echo server:

package main

import (
	"log"

	"github.com/urpc/uio"
)

func main() {
	events := &uio.Events{
		Handler: uio.FuncHandler{
			Open: func(c uio.Conn) {
				log.Println("hello", c.RemoteAddr())
			},
			Read: func(c uio.Conn) error {
				_, err := c.WriteTo(c) // echo everything that arrived
				return err
			},
			Close: func(c uio.Conn, err error) {
				log.Println("bye", c.RemoteAddr(), err)
			},
		},
	}

	log.Fatal(events.Serve(":9527"))
}

Serve accepts several addresses at once, with an optional scheme: ":9527", "tcp6://[::1]:9527", "udp://:5353", "unix:///tmp/app.sock". Once Serve is running (Serve() with no address for a dial-only client), the same Events can dial out with Dial or DialContext, take over an established stream net.Conn with Adopt, or add an address with Listen(addr, opts...). Each connection a listener accepts starts with the Userdata its WithUserdata option names, and closing the returned Listener stops accepting there while the connections it accepted stay open (a UDP listener's peers share its socket and close with it). A packet listener also dials: assert the returned Listener to a PacketListener and DialPeer(raddr, userdata) makes the peer's connection on the listener's own socket — what it sends leaves from the listener's address and the peer's answers reach that connection, as they would had the peer spoken first — which is the entry point for hole punching; WriteTo sends a single datagram the same way.

For the socket options no setter carries, Conn.Control(fn) runs fn with the connection's descriptor — IP_TTL for a NAT probe, IP_TOS, SO_MARK — and the SocketControl options run before a socket connects or binds: WithDialControl on a dial, WithLocalAddr binds the dial's socket first, and WithListenControl runs on a Listen's socket before it binds. fd is valid only for the call, and these are the hooks a hole punch needs; the punching itself is yours.

How it works

Event loops collect readiness, a sharded scheduler keeps each connection's turns serialized on one shard, a connection turn reads and runs your callbacks, and a write turn sends writes from other goroutines

  1. Watch. A few event loops — epoll or kqueue instances, one per four Ps by default — accept connections and collect readiness. They never run your code.
  2. Queue. A ready connection is handed to a sharded worker pool. Its turns go to the shard its key picks — the pool adds shards as connections grow — so its work tends to return to the same CPU, where its socket is still warm in cache. You can supply your own scheduler through Events.Executor.
  3. Serve. A connection's turn reads the socket, runs OnRead, and then flushes every reply the callback wrote in one go. Turns of one connection never overlap; different connections run in parallel.

A write from another goroutine — say, an RPC reply that finishes later — is queued and sent by a short write turn, so it does not wait for a slow read. Only one sender touches a socket at a time, and bytes leave in the order they were written.

Timed turns. SetWakeDeadline schedules an OnTimer for a connection at a time of your choosing, within one scheduler tick of it — for heartbeats, protocol update ticks and idle timeouts; SetWakeInterval repeats it every period. 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. On the native backend the timers live on a per-loop timing wheel that a kernel timer wakes, so an armed timer costs no goroutine and an idle connection none at all; the stdio backend runs one runtime timer per armed connection.

This describes the native epoll/kqueue backend. The portable stdio backend used on Windows (or with -tags stdio) gives each stream connection its own reader and writer goroutines instead.

Protocol layers

A protocol that is not yours to implement — TLS, compression, an auth handshake — can sit between the socket and your handler as a protocol layer. WithLayers names a chain on an endpoint — a Listen, a dial, an adoption — and UIO stacks it under Events.Handler; the first layer in it sits nearest the wire. A Listener carries its one chain for its life; a Dialer may hold defaults each dial overrides.

A wss server is the smallest complete example: a TLS layer, a WebSocket package, and one line joining them. The two directions run through the same stack and mirror each other exactly.

Reading, left to right: the socket hands up TLS records, the TLS layer decrypts them into a plaintext stream, the WebSocket protocol deframes that stream into messages, and your handler sees payloads.

Writing, right to left: SendText becomes a frame, the frame is encrypted into a TLS record, and the record leaves by the same socket.

The same seam carries a datagram transport into the model. ukcp runs KCP — a reliable stream over an unreliable datagram network — as a PacketLayer: on a UDP connection it reads a datagram per turn and hands the layers above a reliable stream, so TLS composes over it exactly as it does over TCP. Above a stream it frames its segments itself, so another KCP or a TLS connection composes below it just as well:

listener, err := events.Listen("udp://:9000",
	uio.WithLayers(ukcp.ServerLayer(ukcp.Options{}), utls.Server(cfg)))
// the Handler reads a TLS stream carried by KCP over UDP

A layer transforms bytes, and UIO carries everything else. Writing one means writing what the protocol changes — nothing more:

type Layer interface {
	Attach(ctx LayerContext) LayerHandler // once per connection
}

type LayerHandler interface {
	OnOpen(ctx LayerContext)                            // start a handshake; Up().Open() when settled
	OnRead(ctx LayerContext) error                      // a turn: read Down(), write Up()
	OnWrite(ctx LayerContext, p []byte) (int, error)    // bytes from above → Down().Write(...)
	OnTimer(ctx LayerContext) error                     // this layer's own timer came due
	OnClose(ctx LayerContext, cause error)
}

Layer is the protocol, configured once; LayerHandler is its instance on one connection; LayerContext is that instance's place in the stack: Down(), the connection below it reads from, Up(), the layer above's input it writes to, and the connection's lifecycle — ctx.Close(cause) says this layer's goodbye and drains the queue like a close from above, ctx.Abort(cause) ends it at once. Down() carries bytes, options and addressing, never a close: a layer ends the connection through the context, so every close runs the stack's one close algorithm from the layer that began it (CloseWrite stays: ending one direction is part of a layer's own protocol). An obfuscation layer is all of this:

type xorHandler struct {
	uio.PassThrough // open at once, pass through what is not overridden
	key byte
}

func (x *xorHandler) OnRead(ctx uio.LayerContext) error {
	in := ctx.Down().PeekChunk()
	_, _ = ctx.Up().Write(xor(in, x.key))
	_, err := ctx.Down().Discard(len(in))
	return err
}

func (x *xorHandler) OnWrite(ctx uio.LayerContext, p []byte) (int, error) {
	if _, err := ctx.Down().Write(xor(p, x.key)); err != nil {
		return 0, err
	}
	return len(p), nil
}

ln, err := events.Listen(addr, uio.WithLayers(
	uio.LayerFunc(func(uio.LayerContext) uio.LayerHandler { return &xorHandler{key: 0x5a} }),
))

examples/xorlayer runs this layer for real, on both ends of one connection, under a second layer that prints the bytes on the wire: go run ./xorlayer in examples shows a message leave as plaintext, cross the wire XOR'd, and arrive as plaintext again.

The layer above — the next layer or your Handler — gets a Conn UIO builds over this one: its reads are what the layer delivered, its writes reach OnWrite, and its addresses, userdata, deadlines and socket options are the connection's own. A layer writes none of that.

One connection through the stack

Every endpoint names its own chain. A Listener carries the one a Listen gave it, fixed for its life: one port, one stack. A Dialer holds the defaults it was built with — events.Dialer(uio.WithLayers(tls)) — and each dial may name its own, replacing them for that connection alone: one Dialer serves wss:// and ws:// alike, the first dial naming the TLS layer and the second WithLayers(PassThroughLayer). DialContext(ctx, addr, uio.WithLayers(tls)) on the Events is the chainless default Dialer naming the chain for that one dial.

uio.WithLayers(kcp, tls, trace) creates one LayerHandler for each connection of that endpoint. The first layer named is closest to the wire; the Handler sees the top layer. The whole path is:

build + open (once per connection)

connection
   │
   ├─ stackDriver.OnOpen
   ├─ Attach(kcp) → Attach(tls) → Attach(trace)
   └─ kcp.OnOpen ─Up().Open()→ tls.OnOpen ─Up().Open()→ trace.OnOpen
      ─Up().Open()→ Handler.OnOpen   (each opens after the one below
      returned — never inside another callback — and the dial settles
      once the Handler's OnOpen returned)

one turn: inbound goes up, outbound goes down

inbound  socket ──► [kcp] ──► [tls] ──► [trace] ──► Handler.OnRead
                    Down().Read  Up().Write   Up().Write   Conn.Read

outbound socket ◄── [kcp] ◄── [tls] ◄── [trace] ◄── Handler.Conn.Write
                    Down().Write Down().Write Down().Write

close

Handler calls Close, or a layer ctx.Close/Abort (walked on a turn)
   └─ closing published once; the close passes downward, goodbyes and
      flushes first on a graceful close ──► the socket drains, then closes
      └─ Handler.OnClose → trace.OnClose → tls.OnClose → kcp.OnClose

Every layer reads the connection ctx.Down() and writes the layer above's input ctx.Up(): Read and Write, the same verbs at every level, up to the Handler's own Conn. A write from above arrives as OnWrite, transforms, and leaves through Down().Write. A due layer timer runs before that layer's OnRead; optional OnWireSent and Flush run when the turn ends.

What UIO guarantees every layer

These are UIO's to keep, not each layer's to remember:

  1. Every turn reaches the layers above, whether or not a layer delivered anything. A wake, or a timer armed higher up, reaches the Handler through any stack — a layer cannot swallow it.
  2. Every layer has a timer of its own. LayerContext.SetTimer arms the layer's, and the Handler's SetWakeDeadline is a slot of its own too: no layer replaces another's.
  3. The turn callbacks never overlap. OnOpen, OnRead, OnTimer, OnWireSent, OnClose and the Handler's callbacks run on the connection's turns, and so does a close's walk: CloseGracefully runs on a turn, whatever asked for the close. The others run where they are called for and may overlap the turns: OnWrite on the writer's goroutine, CloseWrite on the goroutine closing the connection or on the turn that finishes its end, OutboundHeld on writers' and Flush on a turn's or the caller of Flush. State they share needs a lock. UIO never calls a layer from below or from inside another layer's callback — Up().Open() records a request, and the layers above open on the turn's open stage, after the calling callback returned — so a layer may hold its lock while it writes, flushes or closes below.
  4. A connection ends once, top down. The Handler's OnClose comes first, if its OnOpen ran, then every layer's. A connection whose stack never opened — a failed handshake — ends without a Handler callback. Once a close has begun — from the Handler or from any layer, even inside its OnWireSent or Flush — no new call reaches a layer from a turn: writes and flushes return net.ErrClosed, and only OnClose follows. A close asked after that follows its own API's repeated-request contract — a repeated CloseWith reports net.ErrClosed, unless it meets a graceful drain, which it cuts short; CloseGracefully and a layer's Close yield to the close under way — and no second goodbye starts. The close itself is the one caller left: the goodbyes it walks, and the flushes it makes below the layer that began it.
  5. The end of a stream travels up. A layer whose peer ended its stream calls LayerContext.Up().End(); the layer above reads io.EOF after the rest. At the top it closes the connection, or, with AllowHalfOpen, leaves the Handler to end its own half with CloseWrite.
  6. MaxOutboundBuffered refuses whole writes, at the top. The Handler's write is checked against the queue below it before it enters the stack, and reserves its room, so concurrent writers cannot pass the limit together; what a layer writes below is never refused — a TLS record, once encrypted, has to reach the wire.
  7. A graceful close lets the queue leave first. Close on a layered connection closes the socket once what was queued — the layers' goodbyes included — has left, or once it stopped moving for uio.LingerTimeout; what arrives meanwhile is discarded. A CloseWith with any other error, and ctx.Abort, end it at once. A layer closing the connection itself does so through ctx.Close(cause) or ctx.Abort(cause): the same one close algorithm, begun at that layer.
  8. MaxInboundBuffered covers the whole stack. Bytes the layers hold for the Handler count against it with the socket's buffer: a stack holding the limit takes nothing more from the socket until the Handler reads.
  9. Layers carry streams. A packet connection — UDP, IP, unixgram, unixpacket — takes a PacketLayer at the bottom of the chain (ukcp runs KCP as one): that layer reads the datagrams and hands the layers above the stream it makes of them. A chain without one is refused with ErrLayersNeedStream.

A layer carries one connection: one above for each one below. A protocol that opens several streams over one connection — HTTP/2, QUIC — is the Handler's to model, over a connection the layer below it made.

Dials and adopted connections run the same stack

DialContext returns only once the whole stack has opened, and the Conn it returns is the top layer's — encrypted underneath, plaintext to you. Adopt and AdoptContext do the same for a net.Conn you hand over:

client := &uio.Events{}
conn, err := client.DialContext(ctx, "tcp://example.org:443",
	uio.WithLayers(utls.Client(cfg)))
// conn reads and writes plaintext; utls encrypts below it

A layer that fails before the stack opens reports its error from DialContext, and the Handler hears nothing of the connection — no OnOpen, no OnClose. What a layer negotiated is its own to report: uio.FindLayer[T](conn) returns the first layer of type T at or below conn — uio.FindLayer[interface{ State() tls.ConnectionState }](conn) finds the TLS state under any stack — and uio.LayerOf(conn) the one that built conn.

A LayerHandler may also implement optional interfaces:

  • CloseWriter ends one direction in its own protocol (a TLS close_notify). A layer without it does not support CloseWrite — embedding PassThrough does not grant it (PassThroughLayer does, as the layer that changes nothing). UIO calls it only after what was written before CloseWrite has gone below: writes in flight finished, the layer flushed, held output sent.
  • GracefulCloser says goodbye as the layer above closes, told the close's cause.
  • WireCounterObserver hears every byte the socket sends, on the connection's turn — for a protocol whose state moves as its output leaves, a ping's timeout or a close waiting for its frame.
  • OutboundHolder and Flusher are for a layer that holds output of its own, a send window or a compressor's buffer: what it holds counts as queued, and Flush reaches it.
  • TrackedWriter answers when one tracked write has left the wire: ctx.Down().(uio.TrackedWriter).WriteTracked(p) returns a SendReceipt, and a ReceiptObserver hears it on the turn it retires — which is how a protocol knows its own frame is out.

Conn.State() reports where the streams stand — StatePeerEnded, StateWriteShut, StateClosing, StateClosed — read on the connection's turn, replacing the old probe reads.

What it is not

  • Not request middleware. A layer runs once per connection and transforms its byte stream; it never sees a request or a message. Per-message work belongs in OnRead.
  • Observer and Hooks do not run through layers. They count the bytes on the wire, which is what makes them right for traffic accounting; the connection they are told about is the one your Handler holds. They only observe: OnBytesWritten may run inside a layer's write, so it must not write to or close the connection.
  • A chain belongs to an endpoint, not to the Events. A Listen names its chain when the listener is created and keeps it for its life; a dial names one, or takes its Dialer's defaults. An endpoint that names no chain runs plain.
  • The stack is fixed once a connection starts. There is no runtime layer replacement — a protocol that sniffs its first bytes (ALPN, a PROXY header) decides inside one layer, not by trading the stack.
  • Packet connections need a PacketLayer at the bottom. UDP, IP and unixgram/unixpacket are refused with ErrLayersNeedStream unless the first layer of the chain declares it takes packets (CarriesPackets): that layer reads one datagram per turn and hands the layers above a stream — ukcp runs KCP exactly this way. It is never paced; a datagram it does not take is gone, so its own protocol carries the backpressure.
  • A layer's delivery to the layer above is paced (DefaultDeliverBound, or MaxInboundBuffered): the framework stops calling a layer whose delivery is full until the layer above reads. The bound is a pacing threshold, not a cap on one write: the write that crosses it — and any a layer makes from OnOpen, OnWireSent or OnSent — lands whole. A Handler that peeks a whole frame without consuming (ReserveInbound + PeekChunk) therefore sees about one bound's worth from a layer that delivers in chunks; set MaxInboundBuffered to size such frames.

Configuration

Everything is optional; the zero Events is ready to use.

Field Default What it does
Pollers one per 4 Ps: 1–8 native, at least 2 on stdio Number of event loops, never more than GOMAXPROCS.
Executor built-in sharded pool Your own scheduler for connection and write turns (native backend).
MaxBufferSize 4 KiB Bytes read per socket read.
WriteBufferedThreshold off Native backend: callback writes smaller than this are queued for the end of the turn instead of sent at once. Replies written in OnRead are batched either way.
MaxOutboundBuffered off Per-connection limit on unsent bytes; a write past it returns ErrOutboundOverflow.
MaxInboundBuffered off Per-connection limit on read but not yet consumed bytes. Once callbacks leave this much unconsumed, the connection stops reading its socket and TCP flow control slows the peer; a Wake whose OnRead consumes below the limit reads on. A ReserveInbound larger than the limit returns ErrInboundOverflow. A packet connection keeps no buffer to hold and is never paced by it: its bottom PacketLayer carries whatever backpressure its protocol provides.
AllowHalfOpen off Keeps a stream connection open after the peer shuts its writing half: OnRead runs once more, Read reports io.EOF once the buffered bytes are consumed, and the connection can still write until CloseWrite shuts this side's half too; it closes once both halves are shut and the bytes the peer sent have been consumed.
ReusePort off Sets SO_REUSEPORT on listeners.
LockOSThread off Locks each event-loop goroutine to its own OS thread; callback workers are unaffected.

The callbacks are three interfaces, each its own field of Events:

Field Interface Methods
Handler Handler OnOpen, OnRead, OnTimer, OnClose: every connection's lifecycle, data and timers
Observer TrafficObserver OnBytesRead, OnBytesWritten: bytes read and written
Hooks ServeHooks OnStart, OnStop: around Serve

Any type implementing an interface fits its field. FuncHandler adapts plain functions to all three: set it as whichever fields its functions fill, and leave the rest unset. An unset field, or a nil FuncHandler function, costs nothing; the three are read once, when Serve starts.

Backpressure

MaxInboundBuffered alone does not slow a peer: it acts when a callback returns without consuming, and the bytes left behind grow the inbound buffer. So when a connection's data goes somewhere slower — a relay leg, an upstream call, another peer — stop consuming once that destination is behind, and wake the source when it drains:

relay := uio.FuncHandler{
	Read: func(c uio.Conn) error {
		peer := peerOf(c) // the paired connection, e.g. from Userdata
		if peer.OutboundBuffered() >= 256<<10 {
			return nil // the far side is behind: leave the bytes unconsumed
		}
		_, err := c.WriteTo(peer)
		return err
	},
	BytesWritten: func(c uio.Conn, _ int) {
		if c.OutboundBuffered() < 128<<10 {
			_ = peerOf(c).Wake() // the far side drained: resume its held reads
		}
	},
}
events := &uio.Events{MaxInboundBuffered: 256 << 10, Handler: relay, Observer: relay}

Once the unconsumed bytes reach the limit, that connection stops reading and TCP flow control blocks whoever is feeding it, so memory stays bounded without closing anyone. Reads resume by themselves as soon as a callback consumes below the limit; but while they are held no I/O event arrives to run that callback, so it takes a Wake — it carries no data — to trigger it. A handler that always consumes its inbound never reaches the hold and needs none. A write past the destination's own MaxOutboundBuffered would fail with ErrOutboundOverflow instead — the check above stays below it, so a full queue pauses the source rather than erroring.

Going faster

These are optional. Plain Read, Write and WriteTo work on every backend.

Read a TLS record whole. A TLS record carries up to 16 KiB, and crypto/tls reads a record per socket read: the default 4 KiB MaxBufferSize splits every record across four rounds, and each round carries its ciphertext through the stack again. At 16 KiB — the record size, the socket-read cadence the standard library runs at — a TLS layer moves about 1.4× the bytes of the 4 KiB default and ahead of crypto/tls on the same wire; at 64 KiB, four records per read, 1.4–1.8× the default across the hosts we ran, the fastest point on both. Smaller frames lose nothing to the bigger reads: ReserveInbound and PeekChunk read a frame from wherever in the buffer it lies.

Decode in place. PeekChunk returns the first chunk of buffered bytes without copying. For a length-prefixed protocol, ReserveInbound gathers a packet that spans several reads into one chunk, so it can still be decoded in place:

func onData(c uio.Conn) error { // a Handler's OnRead, or a FuncHandler's Data
	var header [4]byte
	for {
		h := c.Peek(header[:]) // copies only if the header spans reads
		if len(h) < 4 {
			return nil // wait for the header
		}
		size := binary.BigEndian.Uint32(h)
		if size > maxPacket {
			return errTooBig // check before reserving: it allocates
		}
		total := 4 + int(size)
		if err := c.ReserveInbound(total); err != nil {
			return err
		}
		chunk := c.PeekChunk()
		if len(chunk) < total {
			return nil // the rest is on its way
		}
		handle(chunk[4:total])
		c.Discard(total)
	}
}

Encode in place. Inside a stream connection's own callback on the native backend, ReserveOutbound hands you room in the send queue to encode a reply into. Anywhere else it returns an error; encode into a pooled buffer and give it away with WriteOwned instead:

if dst, err := c.ReserveOutbound(n); err == nil {
	encode(dst) // fill every byte before the callback returns or flushes
} else {
	buf := uio.AcquireBuffer(n)
	encode(buf.AvailableBuffer()[:n])
	buf.CommitWrite(n)
	if _, err := c.WriteOwned(buf); err == uio.ErrOutboundOverflow {
		uio.ReleaseBuffer(buf) // overflow is the only error that hands it back
	}
}

Rules of the road

  • The inbound methods — Read, WriteTo, Peek, PeekChunk, Discard, InboundBuffered and ReserveInbound — may only be called inside the connection's own callback. Slices they return are valid until the callback returns or consumes more input; copy anything you hand to another goroutine. Builds with -race catch most misuse with a panic.
  • Write, Writev, WriteString, WriteOwned, Flush, Close, CloseWrite, CloseWith and CloseGracefully are safe from any goroutine.
  • CloseWrite shuts a stream connection's writing half after everything accepted has been sent; later writes return net.ErrClosed. On a layered connection it runs the layer's own CloseWrite inline — flushing it, and writing a TLS close_notify — so it may wait on I/O.
  • CloseGracefully closes after everything accepted has been sent: writes are refused from the call, reads go on, and the connection releases once its queue is empty or LingerTimeout passes without progress, reporting leftover output as UnflushedError appended to the cause. A CloseWith ends the wait at once.
  • OnBytesWritten can run concurrently with the connection's other callbacks.
  • Events.Close only requests shutdown and returns at once; Serve returns once everything has stopped, or call Events.Wait from another goroutine.
  • Dial blocks the goroutine that calls it. From a callback, prefer dialing on a goroutine of your own.
  • On the stdio backend, Executor is not used.

The API reference has the full contract of every method.

License

Apache License 2.0

The Go gopher in the banner is based on the original design by Renée French, licensed under CC BY 4.0.

Documentation

Overview

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

Index

Constants

View Source
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.

View Source
const LingerTimeout = 5 * time.Second

LingerTimeout bounds how long a graceful close — Conn.CloseGracefully — waits for its output without progress before it closes with what remains.

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")
	// 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")
	ErrReserveUnsupported = errors.New("uio: outbound reservation needs the connection's own callback")
	// ErrPeerExists reports DialPeer finding the peer already connected.
	ErrPeerExists = errors.New("uio: peer already connected")
)
View Source
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.

View Source
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.

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.

View Source
var ErrUnsupported = fmt.Errorf("unsupported method")

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. A reserve the connection cannot serve reports ErrReserveUnsupported instead.

Functions

func FindLayer added in v1.8.0

func FindLayer[T any](conn LayerDown) (T, bool)

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

Types

type AdoptOption added in v1.8.0

type AdoptOption interface {
	// contains filtered or unexported methods
}

AdoptOption configures one adoption; see Adopt.

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 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. PassThrough implements it by passing CloseWrite to the layer below. UIO runs it once what was written before the call has gone below: writes still in flight into the layer finished, the layer flushed if it is a Flusher, 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 {
	// 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)

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

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

	// 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. A layered connection's Conn does not serve
	// it at all: the layers between would have to be bypassed to fill the
	// queue in place. 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 OnRead callback after previously submitted tasks.
	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

	// YieldRead ends the current read round and schedules remaining buffered or
	// socket data for a later OnRead 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

	// CloseGracefully requests the 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 appended to cause. On a layered connection the
	// layers' goodbyes are said first, and the mode is this call's whatever
	// the cause. A CloseWith at any time ends the wait at once: a drain this
	// call, or a layer's LayerContext.Close, began ends there and then, while
	// a CloseWith that finds a close another CloseWith began joins it.
	// Datagram connections close as CloseWith does: their sends wait for
	// nothing.
	CloseGracefully(cause error) 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 — flushing the layer, 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
}

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 ConnState added in v1.8.0

type ConnState uint32

ConnState reports where a connection's streams stand, as Conn.State and LayerDown.State report it. The bits are independent: a peer-ended connection still writes, a write-shut one still reads.

const (
	// StatePeerEnded reports a peer that ended its stream with everything it
	// sent read — what Read(nil) reporting io.EOF says. A layer above still
	// writing holds it open.
	StatePeerEnded ConnState = 1 << iota
	// StateWriteShut reports this end's writing half ended by CloseWrite.
	StateWriteShut
	// 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.8.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: a Dial naming its chain (WithLayers) runs that chain for its connection alone, so one Dialer serves ws:// and wss:// dials alike. A Listener, by contrast, carries its one chain for its life. Events.Dial is the Events' default Dialer's.

func (*Dialer) Dial added in v1.8.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.8.0

func (d *Dialer) DialContext(dialCtx context.Context, addr string, opts ...DialOption) (Conn, error)

DialContext connects synchronously through this Dialer's Events; see Events.DialContext.

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

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

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

func (ev *Events) Adopt(conn net.Conn, opts ...AdoptOption) (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. With layers installed it returns as DialContext does: once the whole stack opened, with the top layer's connection — the one the Handler holds — and a stack that fails before that reports its error; see AdoptContext to bound the wait.

func (*Events) AdoptContext added in v1.8.0

func (ev *Events) AdoptContext(ctx context.Context, conn net.Conn, opts ...AdoptOption) (Conn, error)

AdoptContext is Adopt with ctx bounding the wait for the layers to open; a stack still opening when ctx ends is closed, and AdoptContext reports the cause. Without layers there is nothing to wait for. With them, like DialContext, it cannot be called on an event loop goroutine.

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, opts ...DialOption) (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, opts ...DialOption) (Conn, error)

DialContext connects synchronously and allows cancellation while resolving or establishing the connection. The connection is registered on the calling goroutine; with layers installed it returns once the whole stack opened, which waits for that connection's turns, so a call from a connection callback waits for the dial and its open stage — 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.8.0

func (ev *Events) Dialer(opts ...DialOption) (*Dialer, error)

Dialer returns a Dialer of ev with opts as its defaults: WithLayers names the chain every dial of it runs unless the dial names its own, and WithUserdata the Userdata its connections start with unless the dial sets its own. It fails on a chain a connection cannot carry; a chain's layers are attached when a dial runs.

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

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. 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) 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 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 Flusher added in v1.8.0

type Flusher interface {
	Flush(ctx LayerContext) error
}

Flusher is implemented by a LayerHandler that holds output it can send now. UIO flushes it at the end of every turn — top down, so what one layer flushes reaches the next — and as a graceful close from above passes it, after its goodbye; it also runs when the layer above calls Flush, before the flush passes below. A turn's flush and a caller's may run at once: a layer that writes below from Flush serializes those writes itself, so what one flush took leaves before the next takes anything, and keeps OutboundHeld off the lock that waits on them. Output a layer holds from a write outside the connection's turns waits for the next turn: such a layer calls LayerContext.Wake, or arms its timer, to have one.

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)
	// Sent hears the receipts of the Handler's own tracked writes over a
	// layer stack; see SentObserver.
	Sent  func(c Conn, r SendReceipt)
	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) OnSent added in v1.8.0

func (h FuncHandler) OnSent(c Conn, r SendReceipt)

OnSent implements SentObserver.

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 GracefulCloser added in v1.8.0

type GracefulCloser interface {
	CloseGracefully(ctx LayerContext, cause error)
}

GracefulCloser is implemented by a LayerHandler with a goodbye to send — a TLS close_notify, a WebSocket Close — when the layer above closes the connection. It runs before the close passes to the layer below, with the close's cause: nil, io.EOF or io.ErrUnexpectedEOF for a graceful close — Close's cause is io.ErrUnexpectedEOF, as the socket's own Close is — an error for an abort.

A graceful close of a layered connection lets what was queued leave first, the goodbyes included: the socket's queue drains, bounded by LingerTimeout without progress, before the connection releases — the socket's own CloseGracefully 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. A layer that closes the connection itself, through LayerContext.Close or Abort, ends it for the layers above too: what they hold is dropped. Its own CloseGracefully runs on a later turn, never inside the callback that asked, and UIO does not flush such a layer on its way — it writes what it holds below itself before it closes.

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 runs one too, so it may arrive with nothing
	// to read. 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 not a
	// callback but 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(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 options, 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 Down, hands the layer above what that became with Up().Write, and writes down with Down().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, [SetTimer], and the Handler's Conn.SetWakeDeadline is a slot of its own too: no layer replaces another's.
  • OnOpen, OnRead, OnTimer, OnWireSent and OnClose run on the connection's turns, which never overlap one another or the callbacks of the layers above. CloseGracefully runs on a turn too — the close walk runs there, 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, OutboundHeld on a writer's, and Flush on a turn's or the caller of Flush. 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 or flushes below, and nothing calls it back meanwhile. LayerUp.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 goodbye and the walk below on the turn, never inside the call. Send reports, which can come inside a write, reach the layers on a turn; 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, so a layer that closes from OnWireSent or Flush is the last called: a write or flush that comes after returns net.ErrClosed, a close follows its own API's repeated-request contract — a repeated CloseWith reports net.ErrClosed (one that meets a graceful drain cuts it short instead), while CloseGracefully and a layer's Close yield to the close under way — and only OnClose follows. The close itself is the one caller left: the goodbyes it walks, and the flushes it makes 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 Up().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 LayerContext added in v1.8.0

type LayerContext interface {
	// Down is the connection below: the socket, for the first layer
	// installed; the one the layer below built, for the others. Its inbound
	// methods — Peek, PeekChunk, Discard, Read — are this layer's to call, in
	// OnRead and OnTimer; its writes, options and addressing at any time.
	// Its Userdata is the connection's, and its SetWakeDeadline arms this
	// layer's own timer, as SetTimer does. It carries no lifecycle: see
	// Close and Abort.
	Down() LayerDown

	// Up is the layer above's input: write to it, end it, open it.
	Up() LayerUp

	// Close ends the connection from this layer, gracefully: writes are
	// refused at once, and on the connection's next turn this layer's goodbye
	// says first, with cause, then the layers below say theirs, and the
	// socket drains what was accepted before it closes — the same algorithm
	// as a close from above, begun here. 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(cause error) error

	// Abort ends the connection at once from this layer: goodbyes are told
	// the cause — on the next turn, as Close's are — but nothing is flushed
	// or drained, what the layers above it hold is dropped, and the socket
	// closes. The mode is this call's, never read back from the cause.
	Abort(cause error) error

	// SetTimer arms this layer's own timer for when; a zero time stops it.
	// Down's SetWakeDeadline and SetWakeInterval arm the same timer.
	SetTimer(when time.Time) error

	// Wake runs a turn of the connection.
	Wake() error
}

LayerContext is a layer's handle on its place in one connection's stack: a small hub with two faces. Down is the connection below, Up the layer above's input — everything the layer does goes through one of them.

type LayerDown added in v1.8.0

type LayerDown interface {
	io.Reader
	io.Writer
	io.StringWriter
	io.ByteWriter

	LocalAddr() net.Addr
	RemoteAddr() net.Addr
	Userdata() any
	SetUserdata(value any)
	SetLinger(secs int) error
	SetNoDelay(nodelay bool) error
	SetKeepAlive(keepalive bool) error
	SetKeepAlivePeriod(secs int) error
	Control(fn func(fd uintptr)) error
	SetReadBuffer(size int) error
	SetWriteBuffer(size int) error
	SetDeadline(t time.Time) error
	SetReadDeadline(t time.Time) error
	SetWriteDeadline(t time.Time) error

	Peek(b []byte) []byte
	PeekChunk() []byte
	Discard(n int) (int, error)
	InboundBuffered() int
	OutboundBuffered() int
	ReserveInbound(n int) error
	Writev(vec [][]byte) (int, error)
	WriteOwned(buffer *Buffer) (int, error)
	ReserveOutbound(n int) ([]byte, error)
	Flush() 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

	Wake() error
	SetWakeDeadline(when time.Time) error
	SetWakeInterval(interval time.Duration) error
	YieldRead() error
	CloseWrite() error
}

LayerDown is the connection below a layer as the layer sees it: its bytes, its options and its addressing — Conn without the lifecycle verbs, because a layer ends the connection through LayerContext.Close or LayerContext.Abort, where the stack runs the one close algorithm from the layer that began it. CloseWrite stays: ending the writing half one direction is part of a layer's own protocol.

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 Up().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 Down, consumes
	// them with Discard, and hands up what they became with
	// Up().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 Down().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 LayerDown) 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 LayerUp added in v1.8.0

type LayerUp 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. Call it in OnRead or
	// OnTimer.
	End()

	// Open opens the layers above, once the layer's negotiation settled — at
	// once from OnOpen if it has none. A dial returns once the top layer
	// opened. Call it on the connection's turn.
	Open()

	// 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 up:
	// Write appends where Reserve's room begins. Call both in OnRead or
	// OnTimer.
	Reserve(n int) []byte
	Commit(n int)

	// Buffered is how many written bytes the layer above has not read.
	Buffered() int

	// Yield tells UIO the layer stopped short of what it could write up —
	// its bound was reached, with bytes waiting below or in its own buffers —
	// so the next read above runs a turn to take the rest. A layer that
	// writes up everything it is given never needs it.
	Yield()
}

LayerUp is the layer above's input, as the layer below writes to it. Write always takes all of p and never fails. The framework paces the layer, not its writes: once a layer's delivery to the layer above reaches DefaultDeliverBound — Events.MaxInboundBuffered, when set — the framework stops calling that layer's OnRead until the layer above reads, so a layer never paces its own writes. What one write adds is not capped: the write that crosses the bound, and any made from OnOpen, OnWireSent or OnSent, takes the delivery past it by that write's size. A layer may hold the Up it got. Its methods run on the connection's turn — in OnOpen, OnRead or OnTimer; Write also in OnWireSent and OnSent, whose turns carry what it wrote — and a call made anywhere else races the turn.

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 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. A graceful close waits for the socket's queue alone; a holder's bytes travel there through Flush. OutboundHeld runs on writers' goroutines and in send reports, 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 Flush and 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 Down'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 ReceiptObserver added in v1.8.0

type ReceiptObserver interface {
	OnSent(ctx LayerContext, r SendReceipt)
}

ReceiptObserver is implemented by a LayerHandler whose tracked writes it wants to hear about: OnSent runs on the connection's turn, once per receipt, and may write — a write it makes gets the turn that carries it. Receipts retire when the wire passes them, roughly in write order: a target is a wire position, so a layer whose output shrinks below it (a compressor holding plaintext) can retire a later write first. A receipt still outstanding when the close begins is not reported — once a close starts no layer call follows but the close itself, and OnClose is the notice.

type SendReceipt added in v1.8.0

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

SendReceipt marks one tracked write's place on the wire. The write has left once WireSent reaches the receipt's position, the queue below the connection it entered is empty — everything handed down left, whatever the counts say — or the connection ended; on an end the receipt is not reported, and the layer's OnClose is the notice. The zero value marks no bytes and is never reported.

type SentObserver added in v1.8.0

type SentObserver interface {
	OnSent(c Conn, r SendReceipt)
}

SentObserver is ReceiptObserver for the Handler above the stack: its Conn is the top layer's, and a tracked write it makes below gets its receipt here — FuncHandler's Sent field is the same notice. OnSent runs on the connection's turn, under the rules ReceiptObserver states.

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 SocketControl added in v1.8.0

type SocketControl func(network, addr string, fd uintptr) error

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 TrackedWriter added in v1.8.0

type TrackedWriter interface {
	WriteTracked(p []byte) (int, SendReceipt, error)
}

TrackedWriter is implemented by the connection below a layer — what LayerContext.Down returns — when it can report when one of its writes has left the wire: WireCounter tells a layer where the wire is, and a tracked write tells it where its own bytes are.

n, r, err := ctx.Down().(uio.TrackedWriter).WriteTracked(p)

The receipt is the write's output position, taken once the write returned: above layers that add or remove bytes, it counts the position the write left at, never one guessed from byte counts. A path through an OutboundHolder gives none — the flush that sends held bytes may expand them — so such a receipt retires when the queue below is empty, and that is the only promise it makes. A layer that wants the notice implements ReceiptObserver; a Handler, whose Conn at the top of the stack is also a TrackedWriter, hears it through SentObserver.

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 WireCounter added in v1.8.0

type WireCounter interface {
	WireQueued() uint64
	WireSent() uint64
}

WireCounter is implemented by the Conn a layer builds: positions on the wire, below every layer. WireSent is what the socket reported sent so far, and only grows. WireQueued is where the queue below this Conn ends: what the socket was handed, with what the layers below — this Conn's own layer and those under it, never those above — still hold for it.

A protocol above layers that change how many bytes go out follows its own output by them: what it wrote has left once WireSent reaches the WireQueued it read after writing — never before. The reading is no earlier than the true end, and may be later: other writers' bytes count too, a layer handing bytes down as it is read counts them twice, and bytes a layer holds count as they are, though it may send fewer. So a target may never be reached; once the Conn's OutboundBuffered is zero, everything written to it left, whatever WireSent says. A LayerHandler that would rather be told than poll implements WireCounterObserver: OnWireSent is WireSent's change, pushed.

type WireCounterObserver added in v1.8.0

type WireCounterObserver interface {
	OnWireSent(ctx LayerContext, n int)
}

WireCounterObserver watches the WireCounter every layered Conn shares: OnWireSent is its WireSent moving, pushed. A protocol whose state moves as its output leaves — a ping whose timeout starts once it is on the wire, a close that waits for its frame to go — implements it instead of polling. OnWireSent reports n bytes the socket sent since the last call, counted on the wire: below every layer, so a layer under which others add or remove bytes cannot match n to its own. What it can rely on is the queue: once Lower's OutboundBuffered is zero, everything it wrote left. It runs on the connection's turn — the one running as the send finished, or one the report asks for — as the turn ends, possibly more than once before that turn ends, and may write: the socket may report a send inside the write that made it, where no layer can be called.

There is no observing the wire the other way, because a layer never needs to be told what arrived: it reads what reached it itself, from Lower, on its own OnRead, so inbound has no hidden progress to report. Outbound does: what a layer wrote below leaves later, transformed by layers it cannot see, and only the socket knows when.

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