uws

package
v1.6.0 Latest Latest
Warning

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

Go to latest
Published: Oct 10, 2026 License: Apache-2.0 Imports: 21 Imported by: 2 modules, 1 package

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

uws

uws is an asynchronous WebSocket implementation built on UIO. It implements RFC 6455 framing and message rules, and RFC 7692 permessage-deflate.

Server

import (
	"context"
	"log"
	"net/http"

	"github.com/urpc/uio"
	"github.com/urpc/uio/uws"
)

type handler struct{}

func (handler) OnOpen(*uws.Conn) {}

func (handler) OnMessage(conn *uws.Conn, message uws.Message) {
	if message.Type == uws.TextMessage {
		_ = conn.SendText(message.Payload)
	} else {
		_ = conn.SendBinary(message.Payload)
	}
}

func (handler) OnClose(*uws.Conn, uws.CloseEvent) {}

server := uws.NewServer(handler{})
server.CheckOrigin = func(*http.Request) bool { return true }
server.EnableCompression = true
server.MaxMessageSize = uws.DefaultMaxFramePayload
server.Events.MaxOutboundBuffered = int(server.MaxMessageSize) + 14
log.Fatal(server.Serve(":8080"))

The same Server also implements http.Handler. Start its UIO event loops without a listener before accepting HTTP requests:

server := uws.NewServer(handler{})
ready := make(chan struct{})
serveDone := make(chan error, 1)
server.Events.OnStart = func(*uio.Events) { close(ready) }
go func() { serveDone <- server.Serve() }()
select {
case <-ready:
case err := <-serveDone:
	log.Fatal(err)
}

httpServer := &http.Server{
	Addr:    ":8080",
	Handler: server,
}
defer server.Close(nil)
log.Fatal(httpServer.ListenAndServe())

Server.Serve accepts multiple listening addresses, or no address for use as an http.Handler.

Calling ServeHTTP before Serve is ready returns HTTP 500 and does not start UIO implicitly. The Handler adapter supports plain HTTP/1.1 TCP connections. It validates the request, hijacks it, rejects any client bytes already buffered after the HTTP header, and transfers the socket to UIO before sending the 101 response. Local TLS termination and HTTP/2 cannot be transferred to the native poller; place a TLS proxy in front of the HTTP server when those protocols are required. The application remains responsible for shutting down its http.Server, while Server.Close stops UWS connections and UIO event loops. Configure http.Server.MaxHeaderBytes for this path; Server.MaxHeaderBytes applies to the native Server.Serve parser.

Set CheckOrigin to an application-specific policy for browser-facing servers; a nil policy accepts all origins.

Servers and dialers are single-lifecycle objects and cannot be restarted after Close. Their Close methods request transport shutdown without waiting for the calling connection task, so they are safe inside a callback. Server.Serve is the server join point and returns only after all event loops and connection tasks have exited. Connection completion and its cause are reported by OnClose and CloseEvent. Use Userdata and SetUserdata for connection-specific state from ordered connection callbacks; synchronize access when using other goroutines.

Callbacks run in the owning UIO connection task and messages are ordered per connection. Message.Payload is borrowed until OnMessage returns; call Message.Clone before retaining it or passing it to another goroutine.

SendText, SendBinary, and Ping do not wait for socket writability and are safe to call from any goroutine. They can return uws.ErrNotReady, uws.ErrClosed, validation errors, or uws.ErrBackpressure when the message does not fit Events.MaxOutboundBuffered. Transport write errors can also be returned; Ping can report a flush error. A nil return means the message was accepted in order, not that the peer received it. Accepted data is flushed by the current or next connection task. Concurrent senders wait for each other while a message is encoded and handed to the transport. A message larger than MaxFramePayload is split into fragments. Before the first fragment, UWS checks that the whole wire message fits the outbound limit; a later transport failure can leave a partial message on the wire and closes the connection.

Configure connection-level outbound backpressure with Events.MaxOutboundBuffered; zero disables the transport limit. Size it to hold the largest message that a callback may need to buffer, including all fragment headers. The server example limits incoming messages to one default frame payload so a full-sized echo fits its outbound budget when the queue is otherwise empty.

UWS defaults a zero Events.WriteBufferedThreshold to 4 KiB so consecutive small frames can share transport storage and a flush. Ping and Close still establish explicit flush boundaries. An explicit nonzero threshold is preserved; use a negative value to disable this small-frame coalescing policy.

When one read carries several frames, the replies their callbacks send below that threshold are encoded into a single batch and handed to UIO together when the frames of that read have been delivered. A full batch block can be handed over earlier, so the number of hand-offs and socket writes depends on the frames and transport state. A send from another goroutine during that time, or a Pong the read answers, can join the batch in order. Each batched frame is checked against Events.MaxOutboundBuffered when accepted; an unexpected transport refusal during hand-off aborts the connection. On native transports, a lone small frame can be encoded directly into the outbound queue. The outbound limit still applies per message.

On native Unix transports, UIO runs the complete per-connection path as one serialized connection task: socket I/O, WebSocket parsing and decompression, then OnOpen, OnMessage, or OnClose. A slow connection therefore does not block the event loop or callbacks for other connections. UWS does not add a second executor mailbox or copy message payloads between schedulers.

Set server.Events.Executor or dialer.Events.Executor to provide the UIO connection-task scheduler. Without one, UIO uses taskgo, which keeps about one running worker per P (runtime.GOMAXPROCS(0)) while callbacks use the CPU and adds workers, up to a 512 * runtime.GOMAXPROCS(0) ceiling, while callbacks block; idle workers are retained for 30 seconds so their grown stacks are reused. The executor's typed Submit and SubmitBatch methods must return promptly and must not execute tasks inline; rejection closes the affected connection. A custom taskgo scheduler can still be installed directly:

workers := runtime.NumCPU() * 512
executor := taskgo.NewTask[uio.IOTask](
	func(task uio.IOTask) { task.RunTask() },
	taskgo.WithConcurrency(workers),
	taskgo.WithMaxIdle(30*time.Second),
	taskgo.WithMaxPending(10128), // connection runners plus scheduling headroom
)
server.Events.Executor = executor
defer executor.Stop(context.Background())

Keep the pending limit larger than the expected number of simultaneously ready connections. UIO applies a per-connection transport outbound budget and pauses reads when that connection exhausts its budget. Worker needs depend on the ratio and duration of blocking callbacks; size the pool from a production profile rather than connection count alone. The stdio/Windows backend keeps its dedicated per-connection blocking read/write goroutines and delivers callbacks synchronously from the read path.

On an open connection, Close starts a graceful close handshake: its frame follows every message accepted before it, and no message is accepted after it. Before the handshake completes, Close closes the transport directly. When Events.MaxOutboundBuffered has no room for the frame, the frame waits for the transport to drain instead of failing. The transport then waits for the peer response; CloseTimeout bounds the whole handshake. Protocol errors are reported as close code 1002; invalid UTF-8 uses 1007; oversized messages use 1009.

HandshakeTimeout closes connections that do not complete the HTTP upgrade in time. This bounds per-connection handshake state and protects the descriptor budget from slow or deliberately incomplete handshakes.

Conn.SetDeadline, SetReadDeadline, and SetWriteDeadline forward directly to the UIO transport. Applications own deadline policy; pass a zero time to clear a deadline.

Compression is negotiated only when EnableCompression is set. The default server policy uses no context takeover to bound per-connection state. Set AllowCompressionContextTakeover when retaining compression history is acceptable. Window sizes are negotiated according to RFC 7692.

Text messages are validated as UTF-8 as required by RFC 6455. Trusted-peer deployments may set DisableUTF8Check to skip Text Message validation; close-frame reasons remain validated. Enabling this option is not RFC 6455 compliant.

Client

import (
	"context"
	"log"

	"github.com/urpc/uio/uws"
)

type clientHandler struct{}

func (clientHandler) OnOpen(conn *uws.Conn) {
	_ = conn.SendText([]byte("hello"))
}

func (clientHandler) OnMessage(conn *uws.Conn, message uws.Message) {}

func (clientHandler) OnClose(conn *uws.Conn, info uws.CloseEvent) {
	if info.Err != nil {
		log.Printf("websocket closed: %v", info.Err)
	}
}

dialer := uws.NewDialer()
_, err := dialer.Dial(context.Background(), "ws://127.0.0.1:8080/", clientHandler{})
if err != nil {
	log.Fatal(err)
}

Dial can return errors from setup, the network dial, or writing and flushing the HTTP upgrade request. WebSocket handshake completion is asynchronous: OnOpen means the connection is ready for application messages, while a handshake response failure calls OnClose without a preceding OnOpen and places the cause in CloseEvent.Err.

The context passed to Dial is checked before UIO starts its network dial and then bounds the WebSocket handshake. The network connection itself follows uio.Events.Dial semantics. After OnOpen, the Dial context no longer affects the established connection. OnClose reports the transport or protocol error through CloseEvent.Err.

Linux benchmark

Compare UWS backends and other libraries with the same client version, worker count, payload, connection count, CPU affinity, and warmup. Do not use a single run as a performance claim; report multiple runs and include P99 latency. For a like-for-like comparison, assign disjoint CPU sets to the server and load generator, then give events the same poller count as the stdio server's GOMAXPROCS. In the current 24-CPU Linux test, events slightly outperforms stdio while using substantially less memory. Increasing events or stdio MaxBufferSize from 4 KiB to 16 KiB did not materially improve the tested 1 KiB WebSocket pipeline workload; stdio also retained more memory at 16 KiB. Buffer sizing should follow the actual payload and protocol. Measure both on the deployment platform.

Documentation

Overview

Package uws provides an asynchronous WebSocket server built on UIO.

Index

Constants

View Source
const (
	// DefaultMaxHeaderBytes is the default HTTP upgrade header limit.
	DefaultMaxHeaderBytes = handshake.DefaultMaxBytes
	// DefaultMaxFramePayload is the default wire payload limit for one frame.
	DefaultMaxFramePayload = 16 << 20
	// DefaultMaxMessageSize is the default decompressed message size limit.
	DefaultMaxMessageSize = 64 << 20
	// DefaultCloseTimeout is the default graceful close handshake timeout.
	DefaultCloseTimeout = 5 * time.Second
	// DefaultHandshakeTimeout is the default HTTP upgrade timeout.
	DefaultHandshakeTimeout = 10 * time.Second
)

Variables

View Source
var (
	// ErrClosed reports an operation on a closed connection.
	ErrClosed = errors.New("uws: connection closed")
	// ErrNotReady reports an operation attempted before the handshake completes.
	ErrNotReady = errors.New("uws: handshake not complete")
	// ErrBackpressure reports that the UIO connection outbound queue is full.
	ErrBackpressure = errors.New("uws: outbound queue is full")
	// ErrServerStarted reports a second attempt to run a Server listener after
	// its transport has already started.
	ErrServerStarted = errors.New("uws: server already started")
	// ErrProtocol reports a WebSocket protocol violation.
	ErrProtocol = frame.ErrProtocol
)

Functions

This section is empty.

Types

type CloseEvent added in v1.1.0

type CloseEvent struct {
	// Code is the peer or locally generated WebSocket close status code.
	Code uint16
	// Reason is the optional close reason sent with Code.
	Reason string
	// Err is the transport, protocol, or application error that caused closure.
	Err error
}

CloseEvent describes why a WebSocket connection closed.

type Conn

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

Conn is an established or handshaking WebSocket connection. UIO serializes protocol and handler callbacks per connection; atomics here coordinate external writers, timers, heartbeat scanning, and transport callbacks. The fields every message touches come first, so they share as few cache lines as the struct's size class allows.

func (*Conn) Close

func (c *Conn) Close(code uint16, reason string) error

Close starts a graceful WebSocket close handshake. The Close frame follows every message accepted before it. When the outbound limit has no room for the frame, it waits for the transport to drain instead of failing; either way the connection stops accepting messages, and CloseTimeout bounds the handshake.

func (*Conn) IsClosed

func (c *Conn) IsClosed() bool

IsClosed reports whether the connection has closed.

func (*Conn) LocalAddr

func (c *Conn) LocalAddr() net.Addr

LocalAddr returns the local transport address.

func (*Conn) Ping

func (c *Conn) Ping(payload []byte) error

Ping sends a ping control frame with up to 125 bytes of payload.

func (*Conn) RemoteAddr

func (c *Conn) RemoteAddr() net.Addr

RemoteAddr returns the peer transport address.

func (*Conn) Request added in v1.1.0

func (c *Conn) Request() *http.Request

Request returns the HTTP upgrade request during OnOpen for server connections, whether accepted by Server.Serve or adopted through Server.ServeHTTP. It returns nil afterward — handlers that need it beyond OnOpen must keep it — and for client connections. The request is read-only.

func (*Conn) SendBinary

func (c *Conn) SendBinary(payload []byte) error

SendBinary queues payload as one binary message. The transport flushes accepted data in the connection's current or next I/O task.

func (*Conn) SendText

func (c *Conn) SendText(payload []byte) error

SendText queues payload as one text message. The transport flushes accepted data in the connection's current or next I/O task. payload must be valid UTF-8: it is sent as given, and only received text is validated.

func (*Conn) SetDeadline added in v1.1.0

func (c *Conn) SetDeadline(deadline time.Time) error

SetDeadline forwards the transport read and write deadline. A zero value clears it.

func (*Conn) SetNoDelay added in v1.1.0

func (c *Conn) SetNoDelay(noDelay bool) error

SetNoDelay controls whether the underlying TCP connection uses Nagle's algorithm.

func (*Conn) SetReadDeadline added in v1.1.0

func (c *Conn) SetReadDeadline(deadline time.Time) error

SetReadDeadline forwards the transport read deadline. A zero value clears it.

func (*Conn) SetUserdata added in v1.1.0

func (c *Conn) SetUserdata(value any)

SetUserdata replaces the user data associated with the connection. It is not safe for concurrent use from multiple goroutines.

func (*Conn) SetWriteDeadline added in v1.1.0

func (c *Conn) SetWriteDeadline(deadline time.Time) error

SetWriteDeadline forwards the transport write deadline. A zero value clears it.

func (*Conn) Subprotocol

func (c *Conn) Subprotocol() string

Subprotocol returns the negotiated WebSocket subprotocol, or an empty string.

func (*Conn) Userdata added in v1.1.0

func (c *Conn) Userdata() any

Userdata returns the user data associated with the connection. It is not safe for concurrent use from multiple goroutines.

type Dialer

type Dialer struct {
	// Events configures the underlying UIO transport. Nil uses a default Events.
	Events *uio.Events
	// Subprotocols lists protocols offered in preference order.
	Subprotocols []string
	// MaxHeaderBytes bounds the HTTP upgrade response header. Zero uses the default.
	MaxHeaderBytes int
	// MaxFramePayload bounds each wire frame payload. On reads, it also bounds
	// aggregate compressed payload across a fragmented message.
	MaxFramePayload uint64
	// MaxMessageSize bounds a complete message after decompression.
	MaxMessageSize uint64
	// EnableCompression offers RFC 7692 permessage-deflate.
	EnableCompression bool
	// CompressionLevel selects the flate level. Zero uses default compression.
	CompressionLevel int
	// DisableUTF8Check skips Text Message UTF-8 validation. This violates RFC
	// 6455 and should only be used with trusted peers. Close reasons remain validated.
	DisableUTF8Check bool
	// CloseTimeout bounds the graceful WebSocket close handshake. A zero value
	// uses DefaultCloseTimeout.
	CloseTimeout time.Duration
	// HandshakeTimeout bounds the HTTP upgrade handshake. A zero value uses
	// DefaultHandshakeTimeout.
	HandshakeTimeout time.Duration
	// contains filtered or unexported fields
}

Dialer creates outbound WebSocket connections over a shared UIO transport. Configure its fields before the first Dial; the first Dial freezes the connection configuration.

func NewDialer

func NewDialer() *Dialer

NewDialer returns a Dialer configured with default transport settings.

func (*Dialer) Close

func (d *Dialer) Close(err error) error

Close permanently stops the dialer, cancels in-flight connection attempts, and requests closure of established connections. Subsequent Dial calls return the first close cause. OnClose reports connection completion.

func (*Dialer) Dial

func (d *Dialer) Dial(ctx context.Context, addr string, handler Handler) (*Conn, error)

Dial starts a WebSocket connection. The supplied context bounds the TCP connection and WebSocket handshake; it no longer affects the connection after OnOpen. The returned connection remains pending until Handler.OnOpen reports handshake success or Handler.OnClose reports a handshake failure. The returned error covers setup, network dial, and upgrade-request write or flush failures. A handshake response failure is reported through OnClose.

type Handler

type Handler interface {
	// OnOpen is called after a successful WebSocket handshake.
	OnOpen(*Conn)
	// OnMessage receives complete messages in wire order.
	OnMessage(*Conn, Message)
	// OnClose is called once after the transport closes. A client handshake
	// failure may call it without a preceding OnOpen.
	OnClose(*Conn, CloseEvent)
}

Handler receives ordered lifecycle and message callbacks for a connection.

type Message

type Message struct {
	// Type identifies whether Payload contains text or binary data.
	Type MessageType
	// Payload is valid until OnMessage returns. Call Clone before retaining it
	// or handing it to another goroutine.
	Payload []byte
}

Message is one complete text or binary WebSocket message.

func (Message) Clone

func (m Message) Clone() Message

Clone returns an independently owned copy of m.

type MessageType

type MessageType uint8

MessageType identifies the payload format of a WebSocket message.

const (
	// TextMessage identifies a UTF-8 text message.
	TextMessage MessageType = 1
	// BinaryMessage identifies a binary message.
	BinaryMessage MessageType = 2
)

type Server

type Server struct {
	// Events configures the underlying UIO transport. Nil uses a default Events.
	Events *uio.Events
	// Handler receives connection lifecycle and message callbacks. It may be nil.
	Handler Handler
	// CheckOrigin accepts an upgrade request. Nil accepts every origin.
	CheckOrigin func(*http.Request) bool
	// Subprotocols lists supported protocols in server preference order.
	Subprotocols []string
	// MaxHeaderBytes bounds HTTP upgrade headers read by the native Serve path.
	// When using ServeHTTP, configure http.Server.MaxHeaderBytes instead.
	MaxHeaderBytes int
	// MaxFramePayload bounds each wire frame payload. On reads, it also bounds
	// aggregate compressed payload across a fragmented message.
	MaxFramePayload uint64
	// MaxMessageSize bounds a complete message after decompression.
	MaxMessageSize uint64
	// EnableCompression enables RFC 7692 permessage-deflate negotiation.
	EnableCompression bool
	// CompressionLevel selects the flate level. Zero uses default compression.
	CompressionLevel int
	// DisableUTF8Check skips Text Message UTF-8 validation. This violates RFC
	// 6455 and should only be used with trusted peers. Close reasons remain validated.
	DisableUTF8Check bool
	// CloseTimeout bounds the graceful WebSocket close handshake. A zero value
	// uses DefaultCloseTimeout.
	CloseTimeout time.Duration
	// HandshakeTimeout bounds the HTTP upgrade handshake. A zero value uses
	// DefaultHandshakeTimeout.
	HandshakeTimeout time.Duration
	// AllowCompressionContextTakeover enables RFC 7692 context takeover for
	// peers that do not request a no-context-takeover parameter. It is disabled
	// by default to bound per-connection compression state.
	AllowCompressionContextTakeover bool
	// HeartbeatInterval enables server pings when positive.
	HeartbeatInterval time.Duration
	// HeartbeatTimeout bounds both the time a ping may remain queued and the
	// time to receive its matching pong after it is written. Zero uses twice
	// the interval.
	HeartbeatTimeout time.Duration
	// contains filtered or unexported fields
}

Server accepts WebSocket connections over a UIO transport. Configure its fields before calling Serve; Serve freezes the connection configuration.

func NewServer

func NewServer(handler Handler) *Server

NewServer returns a Server configured with the default limits.

func (*Server) Close

func (s *Server) Close(err error) error

Close permanently stops the server and requests transport shutdown. Serve returns after all event loops and connection tasks have exited.

func (*Server) Serve

func (s *Server) Serve(addrs ...string) error

Serve starts the event loops and listens on each supplied address. Calling Serve without an address prepares the Server for use as an http.Handler.

func (*Server) ServeHTTP added in v1.1.0

func (s *Server) ServeHTTP(writer http.ResponseWriter, request *http.Request)

ServeHTTP upgrades a plain HTTP/1.1 TCP connection and transfers it from net/http to the Server's UIO event loops. Serve must already be running. TLS and HTTP/2 are not supported.

Directories

Path Synopsis
autobahn
server command
examples
echo command
nethttp command
internal
compress
Package compress implements RFC 7692 message DEFLATE with bounded output and negotiated context takeover.
Package compress implements RFC 7692 message DEFLATE with bounded output and negotiated context takeover.
extension
Package extension parses and negotiates WebSocket extension headers.
Package extension parses and negotiates WebSocket extension headers.
frame
Package frame implements the wire-level WebSocket frame codec.
Package frame implements the wire-level WebSocket frame codec.
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