kolo docsbeta

kolo-transport

Uma conexão QUIC entre dois peers do Kolo, com streams multiplexados e limites rígidos.

Nesta página

A kolo-transport abre conexões QUIC versão 1 (RFC 9000) sobre UDP, protegidas por TLS 1.3 (RFC 9001), com a recuperação de perdas e o controle de congestionamento Reno da RFC 9002 e um controlador BBR opcional segundo Cardwell et al. Ela dá a cada peer streams bidirecionais e unidirecionais, com limites rígidos para dados não lidos, streams e conexões. A conexão é criptografada, mas o peer não é autenticado: a kolo-secure acrescenta a identidade por cima, usando chaves da kolo-id.

Instalação

go get github.com/ciranda-dev/kolo-transport

Compila sem cgo.

Início rápido

Um listener e um dialer em um só programa, em 127.0.0.1. O dialer abre um stream, e o listener devolve o que recebe.

main.go
package main

import (
	"context"
	"fmt"
	"io"
	"log"
	"time"

	kolotransport "github.com/ciranda-dev/kolo-transport"
)

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	l, err := kolotransport.Listen(ctx, "127.0.0.1:0", nil)
	if err != nil {
		log.Fatal(err)
	}
	defer l.Close()
	go func() {
		c, err := l.Accept(ctx)
		if err != nil {
			return
		}
		s, err := c.AcceptStream(ctx)
		if err != nil {
			return
		}
		io.Copy(s, s)
		s.Close()
	}()

	c, err := kolotransport.Dial(ctx, l.Addr().String(), nil)
	if err != nil {
		log.Fatal(err)
	}
	defer c.Close()
	s, err := c.OpenStream(ctx)
	if err != nil {
		log.Fatal(err)
	}
	if _, err := s.Write([]byte("hello kolo")); err != nil {
		log.Fatal(err)
	}
	s.Close()
	reply, err := io.ReadAll(s)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("%s\n", reply)
}

O programa imprime hello kolo. s.Close() encerra só o lado de envio, então o dialer ainda consegue ler a resposta.

Referência da API

A referência da API é gerada a partir do código Go e está em inglês.

Pacote kolotransport · github.com/ciranda-dev/kolo-transport · v0.1.0

Package kolotransport carries multiplexed streams over one QUIC (RFC 9000) connection between two Kolo peers.

It does not authenticate the peer. Each Listener presents an ephemeral self-signed certificate and the dialer accepts any such certificate, so TLS 1.3 gives confidentiality and integrity against passive observers but no identity, and an active man in the middle is not detected. Identity must come from a higher layer, for example kolo-id signatures over ExportKey.

Experimental: the API may change before v1.0.0.

Constantes

const ALPN = "kolo/0"

ALPN is the TLS application protocol both ends must offer.

const DefaultMaxConnReceiveWindow = 512 << 10

DefaultMaxConnReceiveWindow is the default MaxConnReceiveWindow: 512 KiB.

const DefaultMaxGrownConnReceiveWindow = 8 << 20

DefaultMaxGrownConnReceiveWindow is the default MaxGrownConnReceiveWindow: 8 MiB.

const DefaultMaxGrownMemory = 64 << 20

DefaultMaxGrownMemory is the default MaxGrownMemory: 64 MiB.

const DefaultMaxGrownStreamReceiveWindow = 4 << 20

DefaultMaxGrownStreamReceiveWindow is the default MaxGrownStreamReceiveWindow: 4 MiB.

const DefaultMaxMemory = 1 << 30

DefaultMaxMemory is the default MaxMemory: 1 GiB of receive window.

const DefaultMaxStreamReceiveWindow = 256 << 10

DefaultMaxStreamReceiveWindow is the default MaxStreamReceiveWindow: 256 KiB.

const MaxCode uint64 = 1<<62 - 1

MaxCode is the largest error code QUIC can carry.

const MaxPacketSize = 1200

MaxPacketSize is the largest non-QUIC datagram WritePacket sends and ReadPacket returns.

Variáveis

var (
	// ErrInvalidConfig means a Config field is out of range.
	ErrInvalidConfig = errors.New("kolotransport: invalid config")
	// ErrInvalidArgument means a bad code, close message, ExportKey label, PacketConn, listen or dial address, packet or destination (see the README).
	ErrInvalidArgument = errors.New("kolotransport: invalid argument")
	// ErrClosed means this side closed the listener, connection or stream.
	ErrClosed = errors.New("kolotransport: closed")
	// ErrPeerClosed means the peer closed the connection or no longer has state for it.
	ErrPeerClosed = errors.New("kolotransport: peer closed the connection")
	// ErrRefused means the peer refused the connection, for example because its listener is full.
	ErrRefused = errors.New("kolotransport: connection refused")
	// ErrHandshake means the TLS or QUIC handshake failed.
	ErrHandshake = errors.New("kolotransport: handshake failed")
	// ErrTimeout means the handshake or idle timeout expired.
	ErrTimeout = errors.New("kolotransport: timeout")
	// ErrTransport means a QUIC transport error or another failure of the connection.
	ErrTransport = errors.New("kolotransport: transport error")
	// ErrStreamReset means the peer reset the stream or asked this side to stop sending.
	ErrStreamReset = errors.New("kolotransport: stream reset by peer")
	// ErrMaxDialed means Listener.Dial already has MaxDialed connections open.
	ErrMaxDialed = errors.New("kolotransport: too many dialed connections")
	// ErrStreamCanceled means this side canceled the stream.
	ErrStreamCanceled = errors.New("kolotransport: stream canceled")
)

Tipos

type Config

type Config struct {
	// MaxConns caps the connections of a Listener, handshaking or open. Listener only. Default 100, from 1 to 10000.
	MaxConns int
	// MaxConnsPerIP caps them per source address, the one a connection started from. Listener only. Default 4 (or MaxConns if lower), at most MaxConns.
	MaxConnsPerIP int
	// MaxDialed caps the connections Listener.Dial has open, which MaxConns and MaxConnsPerIP do not count. Listener only. Default 32, from 1 to 10000.
	MaxDialed int
	// MaxIncomingStreams caps the concurrent streams the peer may open, bidirectional and unidirectional each. Default 16, from 1 to 1000.
	MaxIncomingStreams int
	// HandshakeTimeout bounds the whole handshake and the life of a Retry token. Default 10s, from 1s to 60s.
	HandshakeTimeout time.Duration
	// IdleTimeout closes a connection with no network activity. Default 30s, from 1s to 10m.
	IdleTimeout time.Duration
	// KeepAlivePeriod sends a PING after this long without receiving, so connections stay open, also those never accepted.
	// Default 5s (or IdleTimeout/2 if lower), from 500ms to below IdleTimeout.
	KeepAlivePeriod time.Duration
	// MaxMemory must cover (MaxConns + MaxDialed) times MaxConnReceiveWindow (unread data, not heap), in bytes; the default leaves headroom and does not bound heap (see the README). Listener only. Default 1 GiB, from 64 MiB to 64 GiB.
	MaxMemory int64
	// AcceptFunc filters attempts by the source IP a connection starts from, never port or identity; false or a panic refuses.
	// Listener only. Nil allows all.
	AcceptFunc func(remote netip.AddrPort) bool
	// MaxStreamReceiveWindow caps the unread data buffered per stream, in bytes, on Listen and Dial. Advanced. Default 256 KiB (or MaxConnReceiveWindow if lower), from 64 KiB to 16 MiB.
	MaxStreamReceiveWindow int64
	// MaxConnReceiveWindow caps the unread data buffered per connection, in bytes; a node that dials N peers can hold N times it. Advanced. Default 512 KiB, from 64 KiB to 64 MiB, at least MaxStreamReceiveWindow.
	MaxConnReceiveWindow int64
	// WindowGrowth lets Conn.AllowWindowGrowth raise the receive windows of a connection the application trusts, up to the Grown values below; every other connection keeps its initial windows. Default false: no window ever grows.
	WindowGrowth bool
	// MaxGrownStreamReceiveWindow is the largest stream window a trusted connection can reach, in bytes. WindowGrowth only. Default 4 MiB (or MaxStreamReceiveWindow if higher), from MaxStreamReceiveWindow to 16 MiB.
	MaxGrownStreamReceiveWindow int64
	// MaxGrownConnReceiveWindow is the largest connection window a trusted connection can reach, in bytes. WindowGrowth only. Default 8 MiB (or MaxConnReceiveWindow if higher), from MaxConnReceiveWindow and MaxGrownStreamReceiveWindow to 64 MiB.
	MaxGrownConnReceiveWindow int64
	// MaxGrownMemory is the connection window growth all trusted connections of a Listener share, in bytes (a dialed Conn has its own); growth stops when it is used up and returns when a connection ends. WindowGrowth only. Default 64 MiB, from 1 MiB to 64 GiB.
	MaxGrownMemory int64
	// Network selects the UDP network of the socket Listen opens. Listener only. Default "udp4", the only accepted value: IPv6 is refused.
	Network string
	// CongestionControl picks the controller that paces what this end sends: "reno" (the default), "cubic" or "bbr". "bbr" keeps a link full where random loss makes the others crawl, but takes the bandwidth of other flows and holds a standing queue (see the guide).
	CongestionControl string
}

Config sets the limits of a Listener or a dialed Conn. A zero field takes its default. Config is not comparable.

type Conn

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

Conn is a connection to one peer, carrying multiplexed streams.

func Dial
func Dial(ctx context.Context, addr string, cfg *Config) (*Conn, error)

Dial connects to the listener at an IPv4 addr from a new udp4 socket (on loopback for a loopback addr), released when the connection ends.

func (Conn) AcceptStream
func (c *Conn) AcceptStream(ctx context.Context) (*Stream, error)

AcceptStream waits for the next bidirectional stream opened by the peer.

func (Conn) AcceptUniStream
func (c *Conn) AcceptUniStream(ctx context.Context) (*ReceiveStream, error)

AcceptUniStream waits for the next unidirectional stream opened by the peer.

func (Conn) AllowWindowGrowth
func (c *Conn) AllowWindowGrowth() bool

AllowWindowGrowth marks the connection as trusted, so its receive windows can grow up to the MaxGrown values while MaxGrownMemory lasts. Call it once the peer is one the application authorized, such as after a handshake that proved its identity; a connection never marked keeps its initial windows. It reports whether growth is on for the connection: false when Config.WindowGrowth is off or the connection has ended. It is safe to call more than once.

func (Conn) Close
func (c *Conn) Close() error

Close closes the connection with code 0.

func (Conn) CloseWithError
func (c *Conn) CloseWithError(code uint64, msg string) error

CloseWithError closes the connection, sending code and msg to the peer. An invalid code or msg (see ErrInvalidArgument) still closes the connection, with code 0 and no message.

func (Conn) Context
func (c *Conn) Context() context.Context

Context is canceled when the connection ends; its context.Cause is the error the connection's calls return.

func (Conn) ExportKey
func (c *Conn) ExportKey(label string) ([32]byte, error)

ExportKey derives 32 bytes from the TLS session (RFC 9846 exporter); both ends get the same bytes only without a man in the middle. Use a unique non-empty label such as "kolo-<lib>/<purpose>/v0", and sign label, role and key together, never the key alone.

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

LocalAddr returns the local UDP address.

func (Conn) OpenStream
func (c *Conn) OpenStream(ctx context.Context) (*Stream, error)

OpenStream opens a bidirectional stream, waiting while the peer's stream limit is reached. The peer sees the stream only once data or a Close is sent on it.

func (Conn) OpenUniStream
func (c *Conn) OpenUniStream(ctx context.Context) (*SendStream, error)

OpenUniStream opens a unidirectional stream, waiting while the peer's stream limit is reached.

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

RemoteAddr returns the peer's UDP address.

func (Conn) Stats
func (c *Conn) Stats() ConnStats

Stats returns a snapshot of the connection's statistics. It is cheap, does not wait on a network read and is safe from any goroutine. The fields are read one by one, not atomically, so a moving value can disagree with its neighbours. After the connection has ended it returns the zero ConnStats.

type ConnStats

type ConnStats struct {
	// SmoothedRTT is the exponentially weighted moving average of the round-trip time samples (RFC 9002, section 5.3).
	// It is 0 until the current path has a sample, which a new connection has once its handshake completes.
	SmoothedRTT time.Duration
	// MinRTT is the lowest round-trip time seen on the current path, which is close to the propagation delay.
	MinRTT time.Duration
	// LatestRTT is the last round-trip time sample on the current path.
	LatestRTT time.Duration
	// RTTVariation is the mean deviation of the samples from SmoothedRTT (the RTTVAR of RFC 9002), a measure of jitter.
	RTTVariation time.Duration

	// BytesSent counts every byte sent, including packets later declared lost and retransmitted data.
	BytesSent uint64
	// BytesReceived counts every byte received, including duplicates and packets that could not be processed.
	BytesReceived uint64
	// PacketsSent counts every packet sent, including packets later declared lost.
	PacketsSent uint64
	// PacketsReceived counts every packet received, including duplicates and packets that could not be processed.
	PacketsReceived uint64
	// PacketsLost counts the packets of this end the peer did not acknowledge in time, and each congestion signal of ECN
	// (a peer that marks packets can raise it without any loss, as the built-in sender counts it too). A packet that arrives
	// late after it was declared lost still counts, so PacketsLost over PacketsSent is an upper bound of the loss rate.
	PacketsLost uint64
	// BytesLost is the size in bytes of the packets counted in PacketsLost.
	BytesLost uint64

	// CongestionWindow is how many bytes this end may have in flight, as set by the congestion controller.
	// A transfer is limited by the congestion window when BytesInFlight stays near it.
	CongestionWindow uint64
	// BytesInFlight is how many bytes of packets this end sent that the peer has not yet acknowledged and this end has not declared lost.
	BytesInFlight uint64
	// CongestionController is the name of the controller sending on this connection: "reno", "cubic" or "bbr".
	CongestionController string
	// BandwidthEstimate is the bottleneck bandwidth the controller measured, in bytes per second: the highest delivery
	// rate of the last ten round trips. Only "bbr" measures it; it is 0 for "reno" and "cubic" and before the first sample.
	BandwidthEstimate uint64
	// MaxDatagramSize is the largest UDP payload in bytes this end sends on the current path. It starts at the
	// initial size and grows as path MTU discovery succeeds.
	MaxDatagramSize uint64
	// PathChanges counts how often the connection moved to a new network path, for example when the peer's NAT gave it a new port.
	// The RTT fields, the congestion window and BandwidthEstimate start over on a new path.
	PathChanges uint64
}

ConnStats is a snapshot of what a connection measured about its network path and its own traffic. Byte counts are QUIC packet bytes: they include QUIC headers and retransmissions, not UDP or IP headers.

type Error

type Error struct {
	Err  error
	Code uint64
}

Error is a connection or stream error with its numeric code; Unwrap returns one of the sentinels.

func (Error) Error
func (e *Error) Error() string

Error returns the sentinel text and the code.

func (Error) Unwrap
func (e *Error) Unwrap() error

Unwrap returns the sentinel.

type Listener

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

Listener accepts connections on one UDP socket and can dial from it.

func Listen
func Listen(ctx context.Context, addr string, cfg *Config) (*Listener, error)

Listen opens a UDP socket on addr, such as "127.0.0.1:0", and accepts connections on it.

func ListenConn
func ListenConn(ctx context.Context, pc net.PacketConn, cfg *Config) (*Listener, error)

ListenConn is Listen on pc, which the Listener owns and closes, also when ListenConn fails (see the README). quic-go may set the socket's buffer sizes and DF bit.

func (Listener) Accept
func (l *Listener) Accept(ctx context.Context) (*Conn, error)

Accept waits for the next connection whose handshake has completed. Up to 32 that are never accepted stay open until Close.

func (Listener) Addr
func (l *Listener) Addr() net.Addr

Addr returns the local address of the listener.

func (Listener) Close
func (l *Listener) Close() error

Close refuses new connections, closes every connection of the listener with code 0, then the socket. It is safe to call more than once.

func (Listener) Dial
func (l *Listener) Dial(ctx context.Context, addr netip.AddrPort) (*Conn, error)

Dial connects to addr from the listener's socket, with the listener's Config; MaxDialed bounds these connections.

func (Listener) ReadPacket
func (l *Listener) ReadPacket(ctx context.Context, b []byte) (int, netip.AddrPort, error)

ReadPacket waits for the next non-QUIC datagram of at most MaxPacketSize bytes; the sender may be spoofed (see the README). A b shorter than the datagram gets its first len(b) bytes and the rest is dropped without an error; the count is the bytes copied.

func (Listener) WritePacket
func (l *Listener) WritePacket(b []byte, to netip.AddrPort) error

WritePacket sends b as one non-QUIC datagram from the listener's socket, blocking as long as its WriteTo does; b[0]&0xC0 must be 0.

type ReceiveStream

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

ReceiveStream is the receiving end of a unidirectional stream.

func (ReceiveStream) CancelRead
func (s *ReceiveStream) CancelRead(code uint64) error

CancelRead asks the peer to stop sending, with code (0 and ErrInvalidArgument if above MaxCode).

func (ReceiveStream) Read
func (s *ReceiveStream) Read(p []byte) (int, error)

Read reads data from the peer; it returns io.EOF after the peer closed the stream.

func (ReceiveStream) SetReadDeadline
func (s *ReceiveStream) SetReadDeadline(t time.Time) error

SetReadDeadline sets the read deadline; an expired deadline returns os.ErrDeadlineExceeded.

type SendStream

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

SendStream is the sending end of a unidirectional stream.

func (SendStream) CancelWrite
func (s *SendStream) CancelWrite(code uint64) error

CancelWrite abandons the stream with code (0 and ErrInvalidArgument if above MaxCode).

func (SendStream) Close
func (s *SendStream) Close() error

Close ends the stream.

func (SendStream) SetWriteDeadline
func (s *SendStream) SetWriteDeadline(t time.Time) error

SetWriteDeadline sets the write deadline; an expired deadline returns os.ErrDeadlineExceeded.

func (SendStream) Write
func (s *SendStream) Write(p []byte) (int, error)

Write writes data to the peer, blocking while flow control is exhausted.

type Stream

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

Stream is a bidirectional stream. Read and Write may be used from different goroutines.

func (Stream) CancelRead
func (s *Stream) CancelRead(code uint64) error

CancelRead asks the peer to stop sending, with code (0 and ErrInvalidArgument if above MaxCode).

func (Stream) CancelWrite
func (s *Stream) CancelWrite(code uint64) error

CancelWrite abandons the send side with code (0 and ErrInvalidArgument if above MaxCode).

func (Stream) Close
func (s *Stream) Close() error

Close ends the send side; the receive side stays open.

func (Stream) Read
func (s *Stream) Read(p []byte) (int, error)

Read reads data from the peer; it returns io.EOF after the peer closed its send side.

func (Stream) SetDeadline
func (s *Stream) SetDeadline(t time.Time) error

SetDeadline sets the read and write deadlines; an expired deadline returns os.ErrDeadlineExceeded.

func (Stream) SetReadDeadline
func (s *Stream) SetReadDeadline(t time.Time) error

SetReadDeadline sets the read deadline.

func (Stream) SetWriteDeadline
func (s *Stream) SetWriteDeadline(t time.Time) error

SetWriteDeadline sets the write deadline.

func (Stream) Write
func (s *Stream) Write(p []byte) (int, error)

Write writes data to the peer, blocking while flow control is exhausted.

Bom saber

Limites

A v0.1.x só aceita IPv4. Os sockets são udp4. Um endereço IPv6, incluindo a forma v4-mapped ::ffff:a.b.c.d, é recusado com ErrInvalidArgument, e um Network diferente de "udp4" com ErrInvalidConfig. Um nome de host sem endereço IPv4 não é resolvido.

Campos de Config (nil ou zero quer dizer o padrão; fora da faixa é ErrInvalidConfig):

  • MaxConns: 100 conexões por listener, em handshake ou abertas, de 1 a 10000. Acima disso, novas tentativas são recusadas e o dialer recebe ErrRefused.
  • MaxConnsPerIP: 4 por endereço de origem (ou MaxConns, se for menor), de 1 a MaxConns. Acima disso, as tentativas desse endereço são recusadas.
  • MaxDialed: 32 conexões abertas por Listener.Dial, de 1 a 10000. Acima disso, Listener.Dial retorna ErrMaxDialed. Essas conexões não contam para MaxConns nem para MaxConnsPerIP.
  • MaxIncomingStreams: 16 streams simultâneos que o peer pode abrir por conexão, tanto bidirecionais quanto unidirecionais, de 1 a 1000. Acima disso, o OpenStream do peer espera.
  • HandshakeTimeout: 10s, de 1s a 60s. Também é a validade de um token de Retry, então um peer cujo tempo de ida e volta passa de mais ou menos metade desse valor não consegue se conectar.
  • IdleTimeout: 30s, de 1s a 10m. O tempo de inatividade de cada lado é min(o próprio IdleTimeout, max(o IdleTimeout do peer, 5s)), então abaixo de 5s os dois lados podem expirar em momentos diferentes.
  • KeepAlivePeriod: 5s (ou IdleTimeout/2, se for menor), de 500ms até abaixo de IdleTimeout. O keep-alive está sempre ligado.
  • MaxStreamReceiveWindow: 256 KiB de dados não lidos por stream, de 64 KiB a 16 MiB.
  • MaxConnReceiveWindow: 512 KiB de dados não lidos por conexão, de 64 KiB a 64 MiB, e no mínimo MaxStreamReceiveWindow.
  • MaxMemory: 1 GiB, de 64 MiB a 64 GiB. Listen verifica (MaxConns + MaxDialed) × MaxConnReceiveWindow ≤ MaxMemory e, se não for o caso, retorna ErrInvalidConfig. Os padrões precisam de 66 MiB. A verificação cobre os dados não lidos, não o heap.
  • CongestionControl: "reno" (padrão), "cubic" ou "bbr". Qualquer outro valor é ErrInvalidConfig. Veja "Controle de congestionamento" abaixo.
  • WindowGrowth: desligado por padrão. Ligado, Conn.AllowWindowGrowth deixa as janelas de recepção de uma conexão crescerem até MaxGrownStreamReceiveWindow (4 MiB, de MaxStreamReceiveWindow a 16 MiB) e MaxGrownConnReceiveWindow (8 MiB, de MaxConnReceiveWindow a 64 MiB), dentro de MaxGrownMemory (64 MiB, de 1 MiB a 64 GiB, compartilhado pelas conexões de um Listener). As três opções MaxGrown precisam de WindowGrowth.

Valores fixos:

  • Fila de accept: 32 conexões com handshake concluído esperando Accept. Acima disso, novas conexões são recusadas. Chame Accept mesmo em um listener usado só para abrir conexões.
  • Datagramas que não são QUIC: MaxPacketSize é 1200 bytes. WritePacket recusa um datagrama maior, vazio ou com cara de QUIC (b[0]&0xC0 != 0) com ErrInvalidArgument, e ReadPacket descarta um maior. A fila guarda 32 datagramas (cerca de 45 KiB) e descarta o resto, então leia logo.
  • CloseWithError: o código é no máximo MaxCode (2^62-1) e a mensagem tem no máximo 256 bytes. Fora da faixa, a conexão fecha mesmo assim, com código 0, e a chamada retorna ErrInvalidArgument. CancelRead e CancelWrite tratam um código acima de MaxCode do mesmo jeito.
  • ExportKey retorna 32 bytes e precisa de um label não vazio.
  • Os tokens NEW_TOKEN expiram em qualquer idade, mesmo dentro de um mesmo tique do relógio ou depois de o relógio de parede voltar atrás (MaxTokenAge é a menor duração), então toda nova tentativa passa por Retry.
  • Listener.Close fecha depois de 1s um PacketConn que ignora deadlines de leitura.
  • Com ListenConn, a conn precisa transportar datagramas de pelo menos 1280 bytes; tudo o que passar de 1452 bytes é truncado.

O heap não é limitado por MaxMemory. Pelas medições do README, com frames de 1 byte cada byte não lido custa cerca de 176 bytes de heap, e cada byte lido em um stream ainda aberto ocupa cerca de 96. O pior caso por conexão é:

Texto
2 × MaxIncomingStreams × MaxStreamReceiveWindow × 96
  + MaxConnReceiveWindow × 176

Com os padrões, isso dá cerca de 856 MiB por conexão. Para limitar o heap, reduza MaxConns, MaxIncomingStreams ou as janelas, defina GOMEMLIMIT, leia os streams logo e feche os dois sentidos quando terminar.

Transferências mais rápidas para peers de confiança

Um stream move no máximo janela / tempo de ida e volta: com a janela padrão de 256 KiB por stream, uns 21 Mbit/s a 100 ms. As janelas são pequenas porque um peer hostil pode fazer um aplicativo reter até 176 bytes de heap por byte não lido, então elas começam pequenas em toda conexão e só crescem em uma que o aplicativo marcou como de confiança, dentro de um orçamento que todas compartilham.

Go
cfg := &kolotransport.Config{WindowGrowth: true}
l, err := kolotransport.Listen(ctx, "127.0.0.1:0", cfg)
// ...
conn, err := l.Accept(ctx)
// The application learns who the peer is, for example from a handshake that
// proved its key, and decides it is one it wants to serve fast:
if peerIsAuthorized(conn) {
	conn.AllowWindowGrowth()
}
  • A kolo-transport nunca fica sabendo quem é um peer, então não pode decidir. O aplicativo chama Conn.AllowWindowGrowth quando a sua própria camada autenticou o peer e a sua política o admite. Ela retorna false quando WindowGrowth está desligado, que é o padrão e não muda nada, ou quando a conexão terminou.
  • O crescimento é o ajuste automático da janela de recepção que a pilha QUIC tem: uma janela dobra enquanto o aplicativo a lê mais rápido que alguns tempos de ida e volta, até MaxGrownStreamReceiveWindow (4 MiB, até 16 MiB) e MaxGrownConnReceiveWindow (8 MiB, até 64 MiB). Ela nunca encolhe.
  • MaxGrownMemory (64 MiB, de 1 MiB a 64 GiB) é o crescimento que todas as conexões marcadas de um Listener podem reter juntas, as de Listener.Dial incluídas. Um passo de crescimento é recusado quando o orçamento não basta, e o orçamento volta quando a conexão termina. Listen também verifica que MaxMemory cobre as janelas iniciais mais esse crescimento.
  • Ao ligar o crescimento em um socket público, mantenha MaxConnReceiveWindow igual a MaxStreamReceiveWindow: a pilha QUIC não deixa o aplicativo recusar o crescimento da janela de um stream, só o da conexão, então com valores iguais uma conexão que ninguém marcou fica na janela inicial, como sem crescimento.

Medido com 100 Mbit/s em cada sentido e um stream lido tão rápido quanto chega, uma conexão marcada leu na velocidade do enlace, 12,24 MB/s, com 20 ms, 50 ms e 100 ms de ida e volta, contra 10,10, 4,43 e 2,01 MB/s com as janelas fixas.

Controle de congestionamento

Config.CongestionControl escolhe o controlador que dita o ritmo do que esta ponta envia: "reno", o padrão, "cubic" ou "bbr". O Reno corta a janela pela metade a cada pacote perdido, então em um caminho que também perde pacotes ao acaso, como um enlace móvel pode perder, um stream sobre 20 Mbit/s com 1 por cento de perda e 120 ms de ida e volta lê a 1,4 a 1,8 Mbit/s. O BBR estima a velocidade do enlace e não desacelera por perdas isoladas.

Go
cfg := &kolotransport.Config{CongestionControl: "bbr"}
conn, err := kolotransport.Dial(ctx, addr, cfg)
  • Cada ponta dita o ritmo do seu próprio envio, então ligue na ponta que envia os dados, ou nas duas para uma transferência que vai nos dois sentidos. Vale para toda conexão que o Config cria (Dial, Listener.Accept, Listener.Dial), e uma conexão mantém o seu controlador quando um NAT dá uma porta nova a quem disca. Qualquer outro valor é ErrInvalidConfig.
  • Medido em um enlace simulado de 20 Mbit/s em cada sentido, 60 ms de atraso em cada sentido e 1 por cento de perda aleatória em cada sentido, com janelas de 8 MiB: um stream lê a 1,83 Mbit/s com Reno e a 18,86 Mbit/s com BBR. O "cubic" não ajuda nesse caminho, porque recua a cada perda como o Reno. Os caminhos medidos só têm perda aleatória independente, não as rajadas, as reordenações nem os limitadores de uma rede real.
  • O BBR só é tão rápido quanto a janela de recepção: com as janelas padrão um stream move no máximo janela / tempo de ida e volta, então use-o junto com janelas maiores ou com WindowGrowth.
  • Mantenha chamadas e mídia ao vivo em "reno". O BBR mantém uma fila fixa no gargalo (uns 100 ms, 150 ms com um roteador com bufferbloat nas medições) e tira banda dos fluxos Reno que o compartilham: ele é para uma transferência que o usuário pediu e quer rápida, não para tráfego de fundo.
  • Uma conexão BBR guarda uma amostra de 88 bytes por número de pacote entre o pacote mais antigo que ela espera e o mais novo que enviou. O intervalo tem um teto de 40000 números de pacote, então um peer que nunca confirma não consegue fazê-lo crescer: as amostras mais antigas são descartadas, o que só custa amostras de banda. O teto limita isso a 5,5 MiB por conexão BBR. "reno" e "cubic" não têm essa estrutura.

Estatísticas da conexão

Conn.Stats() retorna um retrato ConnStats do que uma conexão mediu. É barato (algumas leituras atômicas), nunca bloqueia pela rede, é seguro de qualquer goroutine e retorna o valor zero depois que a conexão termina, então leia antes de fechar a conexão se quiser os números finais. Cada campo é lido separadamente, então dois campos podem não bater em uma amostra.

Go
s := conn.Stats()
fmt.Printf("rtt %v (min %v) window %d in flight %d lost %d of %d packets via %s\n",
	s.SmoothedRTT, s.MinRTT, s.CongestionWindow, s.BytesInFlight, s.PacketsLost, s.PacketsSent, s.CongestionController)
  • SmoothedRTT, MinRTT, LatestRTT e RTTVariation: o tempo de ida e volta do caminho atual e a variação dele.
  • BytesSent, BytesReceived, PacketsSent e PacketsReceived: pacotes QUIC durante toda a conexão, com retransmissões e duplicados.
  • PacketsLost e BytesLost: pacotes que esta ponta enviou e que não foram confirmados a tempo. Um sinal de congestionamento ECN conta como um pacote perdido.
  • CongestionWindow e BytesInFlight: o que o controlador permite em voo e o que está em voo agora.
  • CongestionController: "reno", "cubic" ou "bbr". BandwidthEstimate: a banda do gargalo que o BBR mediu, em bytes por segundo, 0 nos outros dois.
  • MaxDatagramSize: a maior carga UDP que esta ponta envia no caminho atual, no máximo 1452 bytes. PathChanges: quantas vezes a conexão passou para um caminho novo; os campos de ida e volta, a janela e a estimativa recomeçam em um caminho novo.

BytesInFlight perto de CongestionWindow quer dizer que o controlador limita a transferência. Um SmoothedRTT bem acima de MinRTT quer dizer que há uma fila no caminho. BytesInFlight bem abaixo de CongestionWindow com uma transferência lenta quer dizer que o limite não é a rede: a aplicação não escreve rápido o bastante, ou as janelas de recepção do peer estão cheias.

Segurança

  • AcceptFunc filtra pelo IP de origem, não pela identidade. Filtre pelo IP, nunca pela porta: um token de Retry só prova o IP, e pode ser reaproveitado a partir desse IP durante HandshakeTimeout. Um peer pode mover a sua conexão para outro endereço depois do handshake. Se AcceptFunc retornar false ou entrar em pânico, a tentativa é recusada. Ela roda na goroutine que trata todas as novas tentativas, então mantenha a função rápida e sem bloqueio.
  • O remetente de ReadPacket pode estar falsificado. Não disque para ele, e não responda com mais bytes do que ele enviou, até que ele prove que recebe nesse endereço. Datagramas que não são QUIC não passam pelo filtro de AcceptFunc e não têm nenhuma proteção.
  • Dial, Listener.Dial e WritePacket recusam destinos com porta 0, IPv6, não especificados, multicast, 0.0.0.0/8 e 240.0.0.0/4. Endereços de loopback, privados, link-local e de broadcast de sub-rede são permitidos, então filtre qualquer endereço que um peer fornecer antes de abrir conexão com ele ou gravar nele.
  • Os sockets que Listen e Dial criam têm SO_BROADCAST desligado. ListenConn deixa como está.
  • Os erros nunca incluem texto vindo do peer, só um código numérico.

Limites conhecidos

  • Experimental. A API pode mudar antes da v1.0.0.
  • Os datagramas QUIC não são expostos na v0.1.x.
  • A kolo-transport carrega a própria cópia da sua implementação de QUIC, uma versão fixada mais um patch: o gancho para um controlador de congestionamento e os contadores que o Conn.Stats lê. Um script e um teste verificam que a cópia é a versão fixada mais esse patch e nada mais. Uma correção da implementação de QUIC só chega à kolo-transport quando a cópia é atualizada.
  • O Dial do pacote não tem limite de conexões, então um nó que abre conexão com N peers pode acumular N × MaxConnReceiveWindow de dados não lidos.
  • Sem limite: o número de endereços distintos (peers em mais de MaxConns / MaxConnsPerIP endereços ainda podem ocupar todo o MaxConns), a CPU e a banda gastas por pacote, e o buffer de recepção UDP do sistema operacional.
  • Em ListenConn com uma conn que não é *net.UDPConn: sem ECN, sem GSO, sem leituras em lote, e a descoberta de MTU do caminho fica desligada, então os pacotes ficam em 1280 bytes.

Erros

ErroMensagem
ErrClosedkolotransport: closed
ErrHandshakekolotransport: handshake failed
ErrInvalidArgumentkolotransport: invalid argument
ErrInvalidConfigkolotransport: invalid config
ErrMaxDialedkolotransport: too many dialed connections
ErrPeerClosedkolotransport: peer closed the connection
ErrRefusedkolotransport: connection refused
ErrStreamCanceledkolotransport: stream canceled
ErrStreamResetkolotransport: stream reset by peer
ErrTimeoutkolotransport: timeout
ErrTransportkolotransport: transport error

Teste os erros com errors.Is contra os sentinelas. Erros com código são um *Error; use errors.As para ler Code, e o seu Unwrap retorna o sentinela. context.Cause de Conn.Context dá os mesmos erros.

Referências