uws

package
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Sep 5, 2026 License: Apache-2.0 Imports: 20 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/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
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{})
go func() { _ = server.Serve() }()

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

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 on the calling event loop, so they are safe inside a synchronous callback. Server.Serve is the server join point and returns only after all event loops 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 event loop 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 are non-blocking. They return uws.ErrBackpressure when the configured outbound budget is full. Ordinary message sends are accepted into the transport and flushed automatically at its callback or task boundary. Use BeginMessage for large or fragmented messages and call Writer.Close after successful writes. A Writer.Write error aborts the connection and releases write ownership immediately; a later Close only returns the first error. Set MaxOutboundBytes to a negative value to disable the UWS outbound byte limit; zero uses the safe default.

UWS defaults a zero Events.WriteBufferedThreshold to 4 KiB on every transport so consecutive small writes can share a transport flush. Ping, Close, and Writer.Close still establish explicit flush boundaries. An explicit nonzero threshold is preserved; use a negative value to keep immediate-write mode.

Handlers normally run on the I/O event loop and should return promptly. Set Server.Executor or Dialer.Executor to move OnOpen, OnMessage, and OnClose to an application executor. Callbacks for one connection remain serialized. The executor's Submit method must return promptly and return false when its bounded queue is full; use a fixed worker pool for the application work. UWS keeps generous internal mailbox limits as a final guard against an executor that stops making progress. An overloaded connection is closed with code 1013 and ErrApplicationBackpressure; other connections continue to run. If Submit rejects a callback, that connection is closed with ErrExecutorRejected. UWS never falls back to running a rejected callback on the I/O loop, so remaining callbacks, including OnClose, are dropped. Size the executor for the expected concurrent connections, or provide a fair scheduler in front of a bounded worker pool.

*taskgo.Queue implements this executor interface directly (taskgo's Submit API). A typical setup for deep, bursty business calls is:

executor := taskgo.New(
	taskgo.WithConcurrency(8),
	taskgo.WithMaxIdle(time.Second),
	taskgo.WithMaxPending(10128), // connection runners plus scheduling headroom
)
server.Executor = executor
defer executor.Stop(context.Background())

Keep the taskgo pending limit larger than the expected number of simultaneously scheduled connection runners (leave headroom for runner replacement while a worker callback is still returning). UWS independently bounds queued messages with its per-connection and server-wide mailbox limits.

Close sends a close frame and waits for the peer response, bounded by CloseTimeout. 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 protects the event loop and file-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 reports errors that prevent the connection attempt from starting. WebSocket handshake completion is asynchronous: OnOpen means the connection is ready for application messages, while a handshake 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, stdio, and Gorilla with the same client, payload, connection count, CPU affinity, and warmup. Do not use a single run as a performance claim; report multiple runs and include P99 latency. The UIO Unix path is intended for bounded coroutine counts, while stdio is a portability and baseline implementation.

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
	// DefaultMaxOutboundBytes is the default accepted but unsent wire byte
	// limit. It includes room for the largest legal frame header so a maximum
	// sized default frame is not rejected before reaching the transport.
	DefaultMaxOutboundBytes = DefaultMaxFramePayload + 14
	// 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 transport outbound queue is full.
	ErrBackpressure = errors.New("uws: outbound queue is full")
	// ErrApplicationBackpressure reports that the Executor mailbox is full.
	ErrApplicationBackpressure = errors.New("uws: application queue is full")
	// ErrExecutorRejected reports that Executor.Submit rejected a callback.
	ErrExecutorRejected = errors.New("uws: executor rejected callback")
	// ErrWriterClosed reports an operation on a closed message writer.
	ErrWriterClosed = errors.New("uws: message writer is closed")
	// 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.

func (*Conn) BeginMessage

func (c *Conn) BeginMessage(typ MessageType) (*Writer, error)

BeginMessage starts a fragmented message and holds the connection's write ownership until Writer.Close returns. It is non-blocking with respect to the socket; callers must close a successful writer. A Write error aborts the connection and releases write ownership immediately. With compression enabled, writes are compressed incrementally and emitted as continuation frames, so large messages do not need a second full plaintext buffer.

func (*Conn) Close

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

Close starts a graceful WebSocket close 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 until OnOpen returns for a connection adopted through Server.ServeHTTP. It returns nil afterward and for connections accepted by Server.Serve. 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 at its callback or task boundary.

func (*Conn) SendText

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

SendText queues payload as one text message. The transport flushes accepted data at its callback or task boundary.

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
	// MaxOutboundBytes bounds accepted but unsent wire bytes per connection.
	// Zero uses DefaultMaxOutboundBytes; a negative value disables this limit.
	MaxOutboundBytes int
	// 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
	// Executor dispatches OnOpen, OnMessage, and OnClose callbacks away from
	// the I/O event loop. A nil executor preserves synchronous callbacks. If
	// Submit rejects, remaining callbacks are dropped rather than run on the loop.
	Executor Executor
	// 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 unless the configured Executor rejects dispatch.

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 only covers failures that prevent the connection attempt from starting.

type Executor

type Executor interface {
	// Submit schedules callback and reports whether it was accepted.
	Submit(func()) bool
}

Executor runs application callbacks outside the I/O event loop. Submit must return promptly and reports false when a bounded worker queue is full.

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. If Executor rejects
	// dispatch, pending callbacks, including OnClose, may be dropped.
	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
	// MaxOutboundBytes bounds accepted but unsent wire bytes per connection.
	// Zero uses DefaultMaxOutboundBytes; a negative value disables this limit.
	MaxOutboundBytes int
	// 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
	// Executor dispatches OnOpen, OnMessage, and OnClose callbacks away from
	// the I/O event loop. A nil executor preserves synchronous callbacks. If
	// Submit rejects, remaining callbacks are dropped rather than run on the loop.
	Executor Executor
	// 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 closes a connection without a pong. 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 callbacks have exited.

func (*Server) Serve

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

Serve starts the event loops and optionally listens on one 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.

type Writer

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

Writer incrementally sends one fragmented WebSocket message.

func (*Writer) Close

func (w *Writer) Close() error

Close finishes and flushes the message, then releases connection write ownership. After a Write failure it only returns the first error.

func (*Writer) Write

func (w *Writer) Write(payload []byte) (int, error)

Write appends payload to the message. Any error aborts the connection; later calls return the first error without emitting more frames.

Directories

Path Synopsis
autobahn
server command
examples
echo command
nethttp command
internal
frame
Package frame implements the wire-level WebSocket frame codec.
Package frame implements the wire-level WebSocket frame codec.

Jump to

Keyboard shortcuts

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