Documentation
¶
Overview ¶
Package uio provides event-driven connections whose native Unix data path runs in serialized connection tasks outside epoll/kqueue loops.
Index ¶
- Variables
- func ReleaseBuffer(buffer *Buffer)
- type Buffer
- type CompositeBuffer
- type Conn
- type Events
- func (ev *Events) Adopt(conn net.Conn, userdata any) (Conn, error)
- func (ev *Events) Close(err error) error
- func (ev *Events) Dial(addr string, userdata any) (Conn, error)
- func (ev *Events) DialContext(dialCtx context.Context, addr string, userdata any) (Conn, error)
- func (ev *Events) Serve(addrs ...string) (err error)
- func (ev *Events) Wait() error
- type Executor
- type IOTask
- type UnflushedError
Constants ¶
This section is empty.
Variables ¶
var ( ErrOutboundOverflow = errors.New("uio: outbound buffer limit exceeded") ErrInboundOverflow = errors.New("uio: inbound buffer limit exceeded") ErrUnflushedData = errors.New("uio: connection closed with unflushed data") ErrDialOnEventLoop = errors.New("uio: Dial cannot run on an event loop") ErrUDPWriteOnEventLoop = errors.New("uio: UDP write cannot wait on another event loop") ErrReserveUnsupported = errors.New("uio: outbound reservation needs the connection's own callback") )
Functions ¶
func ReleaseBuffer ¶ added in v1.1.0
func ReleaseBuffer(buffer *Buffer)
ReleaseBuffer returns an unsubmitted buffer to the pool. It must be called at most once, and the buffer must not be used afterward.
Types ¶
type Buffer ¶ added in v1.1.0
Buffer is reusable byte storage that can be transferred to a connection with Conn.WriteOwned. Newly acquired writable capacity is not zeroed; every committed byte must be initialized. A Buffer must not be used after its ownership is transferred or it is released.
func AcquireBuffer ¶ added in v1.1.0
AcquireBuffer returns an empty pooled buffer with at least capacity bytes of writable space. Release it when ownership is not transferred to WriteOwned.
type CompositeBuffer ¶
type CompositeBuffer = bytebuf.CompositeBuffer
CompositeBuffer exposes UIO's pooled segmented buffer without introducing a second public buffer type.
type Conn ¶
type Conn interface {
// LocalAddr is the connection's local socket address.
LocalAddr() net.Addr
// RemoteAddr is the connection's remote address.
RemoteAddr() net.Addr
// Userdata returns user-defined connection data. It may be called outside a
// callback, but callers must serialize it with SetUserdata.
Userdata() any
// SetUserdata replaces user-defined connection data. It may be called outside
// a callback, but callers must serialize it with Userdata.
SetUserdata(value any)
// SetLinger sets the behavior of Close on a connection which still
// has data waiting to be sent or to be acknowledged.
//
// If sec < 0 (the default), the operating system finishes sending the
// data in the background.
//
// If sec == 0, the operating system discards any unsent or
// unacknowledged data.
//
// If sec > 0, the data is sent in the background as with sec < 0. On
// some operating systems after sec seconds have elapsed any remaining
// unsent data may be discarded.
SetLinger(secs int) error
// SetNoDelay controls whether the operating system should delay
// packet transmission in hopes of sending fewer packets (Nagle's
// algorithm).
// The default is true (no delay), meaning that data is sent as soon as possible after a Write.
SetNoDelay(nodelay bool) error
// SetKeepAlive sets whether the operating system should send
// keep-alive messages on the connection.
SetKeepAlive(keepalive bool) error
// SetKeepAlivePeriod tells operating system to send keep-alive messages on the connection
// and sets period between TCP keep-alive probes.
SetKeepAlivePeriod(secs int) error
// SetReadBuffer sets the size of the operating system's
// receive buffer associated with the connection.
SetReadBuffer(size int) error
// SetWriteBuffer sets the size of the operating system's
// transmit buffer associated with the connection.
SetWriteBuffer(size int) error
// SetDeadline sets deadline for both read and write.
// If it is time.Zero, SetDeadline will clear the deadlines.
SetDeadline(t time.Time) error
// SetReadDeadline sets the deadline for future Read calls.
// When the user doesn't update the deadline and the deadline exceeds,
// the connection will be closed.
// If it is time.Zero, SetReadDeadline will clear the deadline.
SetReadDeadline(t time.Time) error
// SetWriteDeadline sets the deadline for future data writing.
// If it is time.Zero, SetWriteDeadline will clear the deadline.
SetWriteDeadline(t time.Time) error
// Peek returns the next len(b) bytes without advancing the inbound buffer.
// It may only be called from a connection callback.
Peek(b []byte) []byte
// PeekChunk returns the first contiguous inbound chunk without advancing it.
// The returned slice is valid only until Discard or the callback returns.
// It may only be called from a connection callback.
PeekChunk() []byte
// Discard advances the inbound buffer with next n bytes, returning the number of bytes discarded.
// It may only be called from a connection callback.
Discard(n int) (int, error)
// InboundBuffered returns a inbound buffer data length.
// It may only be called from a connection callback.
InboundBuffered() int
// OutboundBuffered returns payload bytes accepted by this connection but not
// yet written to the socket.
OutboundBuffered() int
// WriterTo
// It may only be called from a connection callback.
// Notice: non-blocking interface, should not be used as you use std.
io.WriterTo
// ReadWriteCloser
// Read may only be called from a connection callback. Write and Close are
// safe from other goroutines.
// Stream writes are non-blocking; native UDP writes from outside the owning
// loop wait for that loop's non-blocking datagram send result.
io.ReadWriteCloser
// ByteWriter
// Notice: non-blocking interface, should not be used as you use std.
io.ByteWriter
// StringWriter
// Notice: non-blocking interface, should not be used as you use std.
io.StringWriter
// Writev "writev"-like batch write optimization.
// Notice: non-blocking interface, should not be used as you use std.
Writev(vec [][]byte) (int, error)
// WriteOwned submits buffer without copying and consumes its ownership on
// every return path except ErrOutboundOverflow, which accepts nothing and
// returns the buffer to the caller to resubmit or release. A direct write
// that partially reached the socket and then could not queue its suffix
// reports io.ErrShortWrite instead: that buffer is consumed and the stream
// is being closed, so the partial frame is never resubmitted. For UDP, one
// buffer is sent as one datagram. Native UDP writes from another event loop
// return ErrUDPWriteOnEventLoop.
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 it reserves nothing
// and returns ErrReserveUnsupported, and the caller writes another way.
// 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.
Flush() error
// Wake schedules one OnData callback after previously submitted tasks.
Wake() error
// YieldRead ends the current read round and schedules remaining buffered or
// socket data for a later OnData callback. It may only be called from a
// connection callback.
YieldRead() error
// CloseWith asynchronously releases the connection on its owning event loop.
// On Unix, unsent accepted payload is reported as UnflushedError.
CloseWith(err error) error
}
Conn is a connection managed by Events. On native Unix, socket I/O and callbacks run in one serialized connection task outside the event loop. 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 from outside the owning event loop wait for the datagram's send result. Any other event-loop callback gets ErrUDPWriteOnEventLoop instead of risking a cross-loop wait cycle.
type Events ¶
type Events struct {
// Pollers is the number of event-loop goroutines.
// The default value is 4, capped by runtime.NumCPU(). On Linux, stream
// readiness is collected by one shared data poller instead, so Pollers
// sizes accept, registration, close, deadline and UDP work.
Pollers int
// Executor supplies the native connection-round scheduler. When nil, UIO
// creates a taskgo typed task queue with its built-in concurrency. 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. Native transports pause that connection's reads at 75% of the
// limit and resume them at 50%. A write that would push buffered unsent data
// beyond the limit returns ErrOutboundOverflow. Zero disables the limit.
MaxOutboundBuffered int
// MaxInboundBuffered limits payload left unread after a callback returns.
// Exceeding it closes the connection with ErrInboundOverflow. Zero disables
// the limit.
MaxInboundBuffered int
// OnOpen fires after registration. Lifecycle and data callbacks are
// serialized per connection, while callbacks for different connections may
// run concurrently.
OnOpen func(c Conn)
// OnData fires when inbound data is available. Inbound access methods are
// valid only for this callback invocation.
OnData func(c Conn) error
// OnClose is the final callback for a connection and never overlaps its
// OnOpen or OnData callback.
OnClose func(c Conn, err error)
// OnInbound reports bytes read from the socket before OnData and shares its
// inbound-access scope.
OnInbound func(c Conn, readBytes int)
// OnOutbound reports bytes successfully written to the socket. It may run on
// a backend writer goroutine and does not grant inbound-buffer access.
OnOutbound func(c Conn, writeBytes int)
// OnStart runs synchronously after initialization and before the master
// listener loop begins polling.
OnStart func(ev *Events)
// OnStop runs once after Serve has stopped its loops and connection tasks.
OnStop func(ev *Events)
// contains filtered or unexported fields
}
Events owns listeners, event loops, the native connection-task scheduler, shared read buffers, and application callbacks for one server/dialer lifecycle. Configure it before Serve; an Events value is not restartable.
func (*Events) Adopt ¶ added in v1.1.0
Adopt transfers ownership of an established stream connection to ev. The caller must not use conn after calling Adopt, including when Adopt returns an error. ev must already be serving.
func (*Events) Close ¶
Close publishes shutdown and returns without waiting. Use Wait or the return of Serve as the lifecycle join point.
func (*Events) Dial ¶
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
DialContext connects synchronously from any goroutine except an event loop and allows cancellation while resolving or establishing the connection.
func (*Events) Serve ¶
Serve starts the event loops and listens on each supplied address. Calling Serve without an address starts a dial-only Events.
func (*Events) Wait ¶ added in v1.4.0
Wait blocks until Serve has stopped every loop and connection task, all stdio I/O goroutines have exited, and OnStop has returned. Wait may be called before Serve; Close before Serve completes it immediately. It must not be called from a callback that is itself part of the lifecycle being joined.
type Executor ¶ added in v1.4.0
Executor schedules native connection I/O rounds. Both methods must return promptly. SubmitBatch accepts a prefix and returns its length; every accepted task must run exactly once. Accepted tasks must run asynchronously after the submission method returns; inline execution would block the event loop and is unsupported. The batch slice is callback-scoped, so an executor must copy references it retains after SubmitBatch returns. Submit false means the task was not run; a short SubmitBatch result means the rejected suffix was not run. Rejection closes the affected connection.
type IOTask ¶ added in v1.4.0
type IOTask interface {
RunTask()
}
IOTask is one serialized native connection I/O round.
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
Source Files
¶
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. |
|
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. |
|
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. |
|
Package uws provides an asynchronous WebSocket server built on UIO.
|
Package uws provides an asynchronous WebSocket server built on UIO. |
|
autobahn/server
command
|
|
|
examples/echo
command
|
|
|
examples/nethttp
command
|
|
|
internal/compress
Package compress implements RFC 7692 message and streaming DEFLATE with bounded output and negotiated context takeover.
|
Package compress implements RFC 7692 message and streaming 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. |