uws

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Aug 31, 2026 License: Apache-2.0 Imports: 18 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 (
	"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.CloseInfo) {}

server := uws.NewServer(handler{})
server.CheckOrigin = func(*http.Request) bool { return true }
server.EnableCompression = true
log.Fatal(server.Serve(":8080"))

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

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. Use BeginMessage for large or fragmented messages and always call Writer.Close. The writer holds the connection's write ownership until it is closed.

UWS defaults a zero Events.WriteBufferedThreshold to 4 KiB on every transport and flushes at protocol and callback boundaries. An explicit nonzero value 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. When enabled, each connection keeps at most MaxPendingMessages and MaxPendingBytes queued message data (64 messages and 1 MiB by default), subject to the server-wide MaxPendingTotalMessages and MaxPendingTotalBytes limits (4096 messages and 64 MiB by default). 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. 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.

SlowClientTimeout bounds how long a FullDuplex connection may remain blocked on socket writes. The default is 30 seconds; set it explicitly when an application needs a shorter or longer slow-reader policy.

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.

Client

import (
	"context"
	"log"

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

dialer := uws.NewDialer()
conn, err := dialer.Dial(context.Background(), "ws://127.0.0.1:8080/", handler{})
if err != nil {
	log.Fatal(err)
}
if err := <-conn.Ready(); err != nil {
	log.Fatal(err)
}

Ready is a one-shot handshake result. A connection must be ready before sending application data.

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  = handshake.DefaultMaxBytes
	DefaultMaxFramePayload = 16 << 20
	DefaultMaxMessageSize  = 64 << 20
	// Leave room for the largest legal WebSocket frame header (including a
	// client mask) so a maximum-sized default frame is not rejected by the
	// outbound budget before it reaches the transport.
	DefaultMaxOutboundBytes        = DefaultMaxFramePayload + 14
	DefaultCloseTimeout            = 5 * time.Second
	DefaultHandshakeTimeout        = 10 * time.Second
	DefaultSlowClientTimeout       = 30 * time.Second
	DefaultMaxPendingMessages      = 64
	DefaultMaxPendingBytes         = 1 << 20
	DefaultMaxPendingTotalMessages = 4096
	DefaultMaxPendingTotalBytes    = 64 << 20
)

Variables

View Source
var (
	ErrClosed                  = errors.New("uws: connection closed")
	ErrNotReady                = errors.New("uws: handshake not complete")
	ErrBackpressure            = errors.New("uws: outbound queue is full")
	ErrApplicationBackpressure = errors.New("uws: application queue is full")
	ErrExecutorRejected        = errors.New("uws: executor rejected callback")
	ErrWriterClosed            = errors.New("uws: message writer is closed")
	ErrProtocol                = frame.ErrProtocol
)

Functions

This section is empty.

Types

type CloseInfo

type CloseInfo struct {
	Code   uint16
	Reason string
	Err    error
}

type Conn

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

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 always close the returned writer. 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

func (*Conn) Context

func (c *Conn) Context() any

func (*Conn) IsClosed

func (c *Conn) IsClosed() bool

func (*Conn) LocalAddr

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

func (*Conn) Ping

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

func (*Conn) Ready

func (c *Conn) Ready() <-chan error

Ready returns a one-shot result for the WebSocket handshake. A nil error means the connection is ready for Send or BeginMessage.

func (*Conn) RemoteAddr

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

func (*Conn) SendBinary

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

func (*Conn) SendText

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

func (*Conn) SetContext

func (c *Conn) SetContext(ctx any)

func (*Conn) Subprotocol

func (c *Conn) Subprotocol() string

type Dialer

type Dialer struct {
	Events            *uio.Events
	Subprotocols      []string
	MaxHeaderBytes    int
	MaxFramePayload   uint64
	MaxMessageSize    uint64
	MaxOutboundBytes  int
	EnableCompression bool
	CompressionLevel  int
	// 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
	// SlowClientTimeout closes FullDuplex connections that remain blocked on
	// socket writes. A zero value uses DefaultSlowClientTimeout.
	SlowClientTimeout time.Duration
	// Executor dispatches OnOpen, OnMessage, and OnClose callbacks away from
	// the I/O event loop. A nil executor preserves synchronous callbacks.
	Executor Executor
	// MaxPendingMessages bounds queued application messages per connection when
	// Executor is enabled. Zero uses DefaultMaxPendingMessages.
	MaxPendingMessages int
	// MaxPendingBytes bounds queued application payload bytes per connection
	// when Executor is enabled. Zero uses DefaultMaxPendingBytes.
	MaxPendingBytes int
	// MaxPendingTotalMessages bounds queued application messages across all
	// connections using this dialer. Zero uses DefaultMaxPendingTotalMessages.
	MaxPendingTotalMessages int
	// MaxPendingTotalBytes bounds queued application payload bytes across all
	// connections using this dialer. Zero uses DefaultMaxPendingTotalBytes.
	MaxPendingTotalBytes int
	// contains filtered or unexported fields
}

func NewDialer

func NewDialer() *Dialer

func (*Dialer) Close

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

func (*Dialer) Dial

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

type Executor

type Executor interface {
	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 and OnClose are called once around a successful WebSocket
	// handshake. OnMessage is ordered per connection. With Executor enabled,
	// all three callbacks for one connection are serialized by that executor.
	OnOpen(*Conn)
	OnMessage(*Conn, Message)
	OnClose(*Conn, CloseInfo)
}

type Message

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

func (Message) Clone

func (m Message) Clone() Message

type MessageType

type MessageType uint8
const (
	TextMessage   MessageType = 1
	BinaryMessage MessageType = 2
)

type Server

type Server struct {
	Events            *uio.Events
	Handler           Handler
	CheckOrigin       func(*http.Request) bool
	Subprotocols      []string
	MaxHeaderBytes    int
	MaxFramePayload   uint64
	MaxMessageSize    uint64
	MaxOutboundBytes  int
	EnableCompression bool
	CompressionLevel  int
	// 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
	// SlowClientTimeout closes FullDuplex connections that remain blocked on
	// socket writes. A zero value uses DefaultSlowClientTimeout.
	SlowClientTimeout time.Duration
	// Executor dispatches OnOpen, OnMessage, and OnClose callbacks away from
	// the I/O event loop. A nil executor preserves synchronous callbacks.
	Executor Executor
	// MaxPendingMessages bounds queued application messages per connection when
	// Executor is enabled. Zero uses DefaultMaxPendingMessages.
	MaxPendingMessages int
	// MaxPendingBytes bounds queued application payload bytes per connection
	// when Executor is enabled. Zero uses DefaultMaxPendingBytes.
	MaxPendingBytes int
	// MaxPendingTotalMessages bounds queued application messages across all
	// connections using this server. Zero uses DefaultMaxPendingTotalMessages.
	MaxPendingTotalMessages int
	// MaxPendingTotalBytes bounds queued application payload bytes across all
	// connections using this server. Zero uses DefaultMaxPendingTotalBytes.
	MaxPendingTotalBytes int
	// 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               time.Duration
	HeartbeatTimeout                time.Duration
	// contains filtered or unexported fields
}

func NewServer

func NewServer(handler Handler) *Server

func (*Server) Close

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

func (*Server) Serve

func (s *Server) Serve(addr string) error

type Writer

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

func (*Writer) Close

func (w *Writer) Close() error

func (*Writer) Write

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

Directories

Path Synopsis
autobahn
server command
examples
echo 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