fdp

package module
v0.0.0-...-64606c9 Latest Latest
Warning

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

Go to latest
Published: Dec 24, 2025 License: MIT Imports: 19 Imported by: 0

README

FDP - Fast Datagram Protocol

Go Reference Go Report Card

FDP is a reliable UDP library for Go. It sits between raw UDP and TCP—giving you the speed of UDP with the reliability you need, when you need it.

Built for games, real-time apps, and anything where latency matters.

Why FDP?

UDP is fast but unreliable. TCP is reliable but adds latency. FDP lets you choose per-packet: want guaranteed delivery? Use reliable mode. Don't care if a packet drops? Fire and forget.

Key points:

  • 20-byte header (4 bytes smaller than KCP)
  • 256 channels per connection (no head-of-line blocking)
  • 4 delivery modes (reliable/unreliable × ordered/unordered)
  • Zero-alloc hot paths (~12ns encode/decode)
  • No external dependencies

Install

go get github.com/migueltarga/fdp

Quick Start

Server:

fdp.Serve(":8080", func(conn *fdp.Connection) {
    defer conn.Close()
    for {
        data, err := conn.RecvData()
        if err != nil {
            return
        }
        conn.SendReliable(data)
    }
})

Client:

conn, _ := fdp.Connect("localhost:8080")
defer conn.Close()

conn.SendReliable([]byte("Hello"))
response, _ := conn.RecvData()

Delivery Modes

Pick the right mode for your data:

Mode Reliable Ordered Good for
ReliableOrdered Chat, game state, RPCs
ReliableUnordered File chunks, asset loading
UnreliableOrdered Audio/video streams
UnreliableUnordered Position updates, heartbeats
// Convenience methods
conn.SendReliable(data)    // ReliableOrdered
conn.SendFast(data)        // ReliableUnordered  
conn.SendStream(data)      // UnreliableOrdered
conn.SendUnreliable(data)  // UnreliableUnordered

// Or explicit
conn.Send(channel, data, fdp.ReliableOrdered)

Configuration

Use the builder for common setups:

// Low-latency gaming
conn, _ := fdp.NewConfig().
    Fast().
    NoCongestion().
    Dial("server:8080")

// Lossy network (adds FEC)
conn, _ := fdp.NewConfig().
    FastRecovery().
    Dial("server:8080")

// Encrypted
key := make([]byte, 32)
conn, _ := fdp.NewConfig().
    Secure(key).
    Dial("server:8080")

Or configure manually:

config := &fdp.Config{
    MTU:          1400,
    SendWindow:   32,
    RecvWindow:   128,
    Interval:     10 * time.Millisecond,
    NoDelay:      true,
    FastResend:   2,
    NoCongestion: false,
    Channels:     4,
}

Channels

Channels prevent head-of-line blocking. If you're sending game state on channel 0 and a chat message on channel 1, a dropped packet on channel 0 won't delay the chat.

// Send on specific channels
conn.Send(0, gameState, fdp.ReliableOrdered)
conn.Send(1, chatMessage, fdp.ReliableOrdered)
conn.Send(2, voiceData, fdp.UnreliableOrdered)

// Receive tells you which channel
channel, data, _ := conn.Recv()

io.ReadWriteCloser

For compatibility with standard interfaces:

conn, _ := fdp.Connect("server:8080")
c := fdp.NewConn(conn)

// Now works with anything expecting io.Reader/Writer
io.Copy(c, os.Stdin)

Production Features

Forward Error Correction:

// Can recover up to 3 lost packets per 13-packet group
conn, _ := fdp.NewConfig().
    FEC(10, 3).
    Dial("server:8080")

Encryption (AES-GCM, ChaCha20-Poly1305):

conn, _ := fdp.NewConfig().
    Encrypt(fdp.CipherAESGCM, key).
    Dial("server:8080")

// Or with password
conn, _ := fdp.NewConfig().
    SecureWithPassword("secret", salt).
    Dial("server:8080")

Rate Limiting:

conn, _ := fdp.NewConfig().
    RateLimit(1024 * 1024). // 1 MB/s
    Dial("server:8080")

QoS (DSCP):

conn, _ := fdp.NewConfig().
    DSCP(46). // Expedited Forwarding
    Dial("server:8080")

Benchmarks

On Apple M3 Max:

BenchmarkPacketEncode         100000000    11.74 ns/op    0 B/op    0 allocs/op
BenchmarkPacketDecode          98424526    12.34 ns/op    0 B/op    0 allocs/op
BenchmarkPacketPool           154542519     7.77 ns/op    0 B/op    0 allocs/op
BenchmarkCryptAESGCMEncrypt    2693986   443.80 ns/op    3.1 GB/s
BenchmarkFECEncode               51148    22735 ns/op  450.4 MB/s

Protocol

20-byte header:

 0       4       8      12      16      20
 +-------+-------+-------+-------+-------+
 | conn  |flags  |  ts   |  seq  |  una  |
 +-------+-------+-------+-------+-------+
 | window| len   |ch |fr |     data...   |
 +-------+-------+---+---+---------------+

License

MIT

Documentation

Overview

Package fdp implements the Fast Datagram Protocol, a high-performance reliable UDP networking library combining the best features of KCP and ENet.

Index

Constants

View Source
const (
	// DefaultSendWindow is the default send window size in packets
	DefaultSendWindow = 32

	// DefaultRecvWindow is the default receive window size in packets
	DefaultRecvWindow = 128

	// MinWindow is the minimum window size
	MinWindow = 4

	// MaxWindow is the maximum window size
	MaxWindow = 65535

	// InitialSSThresh is the initial slow-start threshold
	InitialSSThresh = 2

	// MinSSThresh is the minimum slow-start threshold
	MinSSThresh = 2
)

Congestion control constants

View Source
const (
	DefaultMTU            = 1400
	DefaultSendWindowSize = 32
	DefaultRecvWindowSize = 128
	DefaultInterval       = 100 * time.Millisecond
	DefaultTimeout        = 30 * time.Second
	DefaultKeepAlive      = 10 * time.Second
	DefaultFastResend     = 0 // Disabled by default
	DefaultMinRTO         = 100 * time.Millisecond
	DefaultMaxRTO         = 60 * time.Second
	DefaultNoDelayMinRTO  = 30 * time.Millisecond
)

Connection configuration defaults

View Source
const (
	KeySize128 = 16
	KeySize192 = 24
	KeySize256 = 32

	// NonceSize for different ciphers
	NonceAESGCM  = 12
	NonceChaCha  = 12
	NonceXChaCha = 24
	NonceSalsa20 = 24
	NonceAESCFB  = 16 // AES block size

	// PBKDF2 parameters
	PBKDF2Iterations = 4096
	PBKDF2SaltSize   = 16
)

Key sizes

View Source
const (
	// MaxDataShards is the maximum number of data shards
	MaxDataShards = 255

	// MaxParityShards is the maximum number of parity shards
	MaxParityShards = 255

	// MaxTotalShards is the maximum total shards (data + parity)
	MaxTotalShards = 255

	// DefaultDataShards is the default number of data shards
	DefaultDataShards = 10

	// DefaultParityShards is the default number of parity shards
	DefaultParityShards = 3

	// FECHeaderSize is the size of the FEC header prepended to each shard
	FECHeaderSize = 6 // 2 bytes seqid + 2 bytes index + 2 bytes count
)

FEC constants

View Source
const (
	// HeaderSize is the size of the FDP packet header in bytes
	HeaderSize = 20

	// MaxPacketSize is the maximum size of an FDP packet
	MaxPacketSize = 1400

	// MaxPayloadSize is the maximum payload size per packet
	MaxPayloadSize = MaxPacketSize - HeaderSize

	// Protocol version
	ProtocolVersion = 1
)

Protocol constants

View Source
const (
	FlagReliable  uint8 = 1 << 7 // Bit 7: Requires acknowledgment
	FlagOrdered   uint8 = 1 << 6 // Bit 6: Must be delivered in order
	FlagFragment  uint8 = 1 << 5 // Bit 5: Is a fragment of larger message
	FlagACK       uint8 = 1 << 4 // Bit 4: Is an acknowledgment packet
	FlagConnect   uint8 = 1 << 3 // Bit 3: Connection control packet
	FlagCompress  uint8 = 1 << 2 // Bit 2: Payload is compressed
	FlagReserved1 uint8 = 1 << 1 // Bit 1: Reserved
	FlagReserved0 uint8 = 1 << 0 // Bit 0: Reserved
)

Packet flags (8-bit)

View Source
const (
	// TypeDataReliableOrdered is reliable + ordered delivery (like TCP)
	TypeDataReliableOrdered = FlagReliable | FlagOrdered

	// TypeDataReliableUnordered is reliable but can arrive out of order
	TypeDataReliableUnordered = FlagReliable

	// TypeDataUnreliableOrdered is unreliable but ordered (drop old packets)
	TypeDataUnreliableOrdered = FlagOrdered

	// TypeDataUnreliableUnordered is fire and forget
	TypeDataUnreliableUnordered = 0

	// TypeACK is an acknowledgment packet
	TypeACK = FlagACK

	// TypeConnect is a connection control packet
	TypeConnect = FlagConnect

	// TypePing is a keep-alive packet
	TypePing = FlagACK | FlagConnect

	// TypeDisconnect is a disconnect packet
	TypeDisconnect = FlagConnect | FlagReliable
)

Common packet type combinations

View Source
const (
	CmdConnect       uint8 = 1
	CmdConnectAck    uint8 = 2
	CmdDisconnect    uint8 = 3
	CmdDisconnectAck uint8 = 4
	CmdPing          uint8 = 5
	CmdPong          uint8 = 6
)

Command types for connection control packets

View Source
const (
	// RTODefault is the default retransmission timeout in milliseconds
	RTODefault = 200

	// RTOMin is the minimum RTO in milliseconds
	RTOMin = 100

	// RTOMinNoDelay is the minimum RTO in no-delay mode
	RTOMinNoDelay = 30

	// RTOMax is the maximum RTO in milliseconds
	RTOMax = 60000

	// RTOMultiplierNormal is the RTO multiplier for normal mode (TCP uses 2x)
	RTOMultiplierNormal = 2

	// RTOMultiplierNoDelay is the RTO multiplier for no-delay mode (KCP uses 1.5x)
	RTOMultiplierNoDelay = 1.5
)

RTT estimation constants

View Source
const BatchSize = 128

BatchSize is the maximum packets per batch I/O operation.

View Source
const MaxChannels = 256

MaxChannels is the maximum number of channels per connection

Variables

View Source
var (
	ErrCryptDisabled    = errors.New("fdp: encryption is disabled")
	ErrCryptInvalidKey  = errors.New("fdp: invalid key length")
	ErrCryptInvalidData = errors.New("fdp: invalid encrypted data")
	ErrCryptAuthFailed  = errors.New("fdp: authentication failed")
	ErrCryptTooShort    = errors.New("fdp: ciphertext too short")
)

Encryption errors

View Source
var (
	ErrFECDisabled       = errors.New("fdp: FEC is disabled")
	ErrFECInvalidShards  = errors.New("fdp: invalid shard configuration")
	ErrFECTooManyShards  = errors.New("fdp: too many shards")
	ErrFECNotEnoughData  = errors.New("fdp: not enough data shards for recovery")
	ErrFECRecoveryFailed = errors.New("fdp: FEC recovery failed")
)

FEC errors

View Source
var (
	ErrPacketTooSmall   = errors.New("fdp: packet too small")
	ErrPacketTooLarge   = errors.New("fdp: packet too large")
	ErrInvalidHeader    = errors.New("fdp: invalid packet header")
	ErrPayloadMismatch  = errors.New("fdp: payload length mismatch")
	ErrInvalidChannel   = errors.New("fdp: invalid channel ID")
	ErrConnectionClosed = errors.New("fdp: connection closed")
	ErrTimeout          = errors.New("fdp: operation timed out")
	ErrBufferFull       = errors.New("fdp: send buffer full")
	ErrWindowFull       = errors.New("fdp: window full")
)

Errors

Functions

func AcquireBuffer

func AcquireBuffer() []byte

AcquireBuffer gets a byte buffer from the pool. The buffer has capacity MaxPacketSize.

func AcquireCryptBuffer

func AcquireCryptBuffer() []byte

AcquireCryptBuffer gets an encryption buffer from the pool

func AcquireSmallBuffer

func AcquireSmallBuffer() []byte

AcquireSmallBuffer gets a small byte buffer from the pool.

func DeriveKey

func DeriveKey(password []byte, salt []byte) []byte

DeriveKey derives a 32-byte key from a password using PBKDF2

func EncodeACKPayload

func EncodeACKPayload(buf []byte, acks []ACKInfo) (int, error)

EncodeACKPayload encodes ACK information into a payload buffer

func FillRandom

func FillRandom(buf []byte) error

FillRandom fills a buffer using the global entropy source

func RandomBytes

func RandomBytes(n int) []byte

RandomBytes returns n random bytes

func RandomUint32

func RandomUint32() uint32

RandomUint32 returns a random uint32 using the global entropy

func RandomUint64

func RandomUint64() uint64

RandomUint64 returns a random uint64 using the global entropy

func ReleaseACKInfoSlice

func ReleaseACKInfoSlice(s []ACKInfo)

ReleaseACKInfoSlice returns an ACKInfo slice to the pool.

func ReleaseBuffer

func ReleaseBuffer(b []byte)

ReleaseBuffer returns a byte buffer to the pool. The buffer should not be used after calling this.

func ReleaseCryptBuffer

func ReleaseCryptBuffer(b []byte)

ReleaseCryptBuffer returns an encryption buffer to the pool

func ReleaseFragmentAssembly

func ReleaseFragmentAssembly(f *FragmentAssembly)

ReleaseFragmentAssembly returns a FragmentAssembly to the pool.

func ReleasePacket

func ReleasePacket(p *Packet)

ReleasePacket returns a Packet to the pool. The packet should not be used after calling this.

func ReleaseSegment

func ReleaseSegment(s *Segment)

ReleaseSegment returns a Segment to the pool. The segment should not be used after calling this.

func ReleaseSmallBuffer

func ReleaseSmallBuffer(b []byte)

ReleaseSmallBuffer returns a small byte buffer to the pool.

func ResetPoolStats

func ResetPoolStats()

ResetPoolStats resets pool statistics to zero.

func Serve

func Serve(address string, handler func(*Connection)) error

Serve starts a server and calls handler for each connection

func ServeWithConfig

func ServeWithConfig(address string, config *Config, handler func(*Connection)) error

ServeWithConfig starts a server with custom configuration

func SetEntropy

func SetEntropy(reader io.Reader)

SetEntropy sets the global entropy source

Types

type ACKInfo

type ACKInfo struct {
	// Una is the cumulative acknowledgment (all packets before this are received)
	Una uint32

	// Ranges contains selective acknowledgment ranges
	Ranges []ACKRange

	// Timestamp is when the acknowledged packet was received
	Timestamp uint32
}

ACKInfo contains acknowledgment information

func AcquireACKInfoSlice

func AcquireACKInfoSlice() []ACKInfo

AcquireACKInfoSlice gets an ACKInfo slice from the pool.

func DecodeACKPayload

func DecodeACKPayload(buf []byte) []ACKInfo

DecodeACKPayload decodes ACK information from a payload buffer

type ACKList

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

ACKList tracks pending acknowledgments to be sent

func NewACKList

func NewACKList() *ACKList

NewACKList creates a new ACK list

func (*ACKList) Add

func (l *ACKList) Add(sn, ts uint32)

Add adds an acknowledgment to the list

func (*ACKList) Flush

func (l *ACKList) Flush() []ACKInfo

Flush returns and clears all pending acknowledgments

func (*ACKList) Len

func (l *ACKList) Len() int

Len returns the number of pending acknowledgments

type ACKRange

type ACKRange struct {
	Start uint32
	End   uint32
}

ACKRange represents a range of acknowledged sequence numbers (SACK).

type BandwidthControl

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

BandwidthControl manages bidirectional rate limiting.

func NewBandwidthControl

func NewBandwidthControl(sendRate, recvRate int64) *BandwidthControl

NewBandwidthControl creates a new bandwidth controller

func (*BandwidthControl) AllowRecv

func (bc *BandwidthControl) AllowRecv(n int) bool

AllowRecv checks if receiving n bytes is allowed

func (*BandwidthControl) AllowSend

func (bc *BandwidthControl) AllowSend(n int) bool

AllowSend checks if sending n bytes is allowed

func (*BandwidthControl) Disable

func (bc *BandwidthControl) Disable()

Disable disables bandwidth control

func (*BandwidthControl) Enable

func (bc *BandwidthControl) Enable()

Enable enables bandwidth control

func (*BandwidthControl) SetRecvRate

func (bc *BandwidthControl) SetRecvRate(rate int64)

SetRecvRate sets the receive rate limit

func (*BandwidthControl) SetSendRate

func (bc *BandwidthControl) SetSendRate(rate int64)

SetSendRate sets the send rate limit

func (*BandwidthControl) Stats

func (bc *BandwidthControl) Stats() BandwidthStats

Stats returns bandwidth control statistics

func (*BandwidthControl) WaitSend

func (bc *BandwidthControl) WaitSend(n int)

WaitSend waits until n bytes can be sent

type BandwidthStats

type BandwidthStats struct {
	SendThrottledBytes uint64
	SendThrottledCount uint64
	RecvThrottledBytes uint64
	RecvThrottledCount uint64
	SendRate           int64
	RecvRate           int64
}

BandwidthStats holds bandwidth control statistics

type BatchConn

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

BatchConn wraps a UDP connection with sendmmsg/recvmmsg support.

func NewBatchConn

func NewBatchConn(conn net.PacketConn) (*BatchConn, error)

NewBatchConn creates a new batch-capable connection wrapper

func (*BatchConn) Close

func (bc *BatchConn) Close() error

Close closes the batch connection

func (*BatchConn) ReadBatch

func (bc *BatchConn) ReadBatch(msgs []Message, flags int) (int, error)

ReadBatch reads multiple packets in a single syscall. Returns the number of messages read.

func (*BatchConn) SetDSCP

func (bc *BatchConn) SetDSCP(dscp int) error

SetDSCP sets the DSCP/Traffic Class value

func (*BatchConn) SetReadBuffer

func (bc *BatchConn) SetReadBuffer(bytes int) error

SetReadBuffer sets the socket read buffer size

func (*BatchConn) SetWriteBuffer

func (bc *BatchConn) SetWriteBuffer(bytes int) error

SetWriteBuffer sets the socket write buffer size

func (*BatchConn) WriteBatch

func (bc *BatchConn) WriteBatch(msgs []Message, flags int) (int, error)

WriteBatch writes multiple packets in a single syscall. Returns the number of messages written.

type BatchReader

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

BatchReader reads messages in batches

func NewBatchReader

func NewBatchReader(conn *BatchConn, batchSize int) *BatchReader

NewBatchReader creates a batch reader

func (*BatchReader) Read

func (r *BatchReader) Read() ([]byte, net.Addr, error)

Read returns the next message, reading a batch if needed

type BatchWriter

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

BatchWriter accumulates messages for batch writing

func NewBatchWriter

func NewBatchWriter(conn *BatchConn, batchSize int) *BatchWriter

NewBatchWriter creates a batch writer

func (*BatchWriter) Flush

func (w *BatchWriter) Flush() error

Flush sends all pending messages

func (*BatchWriter) Pending

func (w *BatchWriter) Pending() int

Pending returns the number of pending messages

func (*BatchWriter) Write

func (w *BatchWriter) Write(data []byte, addr net.Addr) error

Write adds a message to the batch. Flushes if batch is full.

type BlockCrypt

type BlockCrypt interface {
	Encrypt(plaintext []byte) ([]byte, error)
	Decrypt(ciphertext []byte) ([]byte, error)
	Overhead() int // Returns nonce size + auth tag size
}

BlockCrypt is the interface for encryption/decryption. All implementations are thread-safe.

func NewAESCFB

func NewAESCFB(key []byte) (BlockCrypt, error)

NewAESCFB creates a new AES-CFB encryptor WARNING: AES-CFB provides no authentication - use with caution

func NewAESGCM

func NewAESGCM(key []byte) (BlockCrypt, error)

NewAESGCM creates a new AES-GCM encryptor

func NewBlockCrypt

func NewBlockCrypt(cipherType CipherType, key []byte) (BlockCrypt, error)

NewBlockCrypt creates a BlockCrypt based on cipher type

func NewChaCha20Poly1305

func NewChaCha20Poly1305(key []byte) (BlockCrypt, error)

NewChaCha20Poly1305 creates a new ChaCha20-Poly1305 encryptor

func NewNoneCrypt

func NewNoneCrypt() BlockCrypt

NewNoneCrypt creates a no-op cipher

func NewSalsa20

func NewSalsa20(key []byte) (BlockCrypt, error)

NewSalsa20 creates a new Salsa20 encryptor WARNING: Salsa20 provides no authentication - use with caution

func NewXChaCha20Poly1305

func NewXChaCha20Poly1305(key []byte) (BlockCrypt, error)

NewXChaCha20Poly1305 creates a new XChaCha20-Poly1305 encryptor

type Channel

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

Channel represents an independent stream within a connection. Each channel has its own sequence numbers and ordering, preventing head-of-line blocking between channels.

func NewChannel

func NewChannel(id uint8) *Channel

NewChannel creates a new channel with the given ID

func (*Channel) CleanupStaleFragments

func (c *Channel) CleanupStaleFragments(currentTime, timeout uint32)

CleanupStaleFragments removes fragment assemblies older than timeout

func (*Channel) GetRetransmitSegments

func (c *Channel) GetRetransmitSegments(currentTime, rto uint32, fastResend uint32) []*Segment

GetRetransmitSegments returns segments that need retransmission

func (*Channel) GetSendSegment

func (c *Channel) GetSendSegment() *Segment

GetSendSegment retrieves the next segment to send, if any

func (*Channel) HasData

func (c *Channel) HasData() bool

HasData returns true if there's data available to receive

func (*Channel) ID

func (c *Channel) ID() uint8

ID returns the channel identifier

func (*Channel) IncrementFastACK

func (c *Channel) IncrementFastACK(sn uint32)

IncrementFastACK increments the fast ACK counter for segments before the given sequence

func (*Channel) PendingSend

func (c *Channel) PendingSend() int

PendingSend returns the number of segments waiting to be sent

func (*Channel) ProcessACK

func (c *Channel) ProcessACK(seq uint32, timestamp uint32) *Segment

ProcessACK handles acknowledgment for a sent segment

func (*Channel) ProcessRecv

func (c *Channel) ProcessRecv(seg *Segment)

ProcessRecv handles an incoming segment for this channel. It manages ordering, deduplication, and fragment reassembly.

func (*Channel) ProcessUNA

func (c *Channel) ProcessUNA(una uint32) []*Segment

ProcessUNA handles cumulative acknowledgment

func (*Channel) Recv

func (c *Channel) Recv() []byte

Recv retrieves the next available message from the receive queue. Returns nil if no message is available.

func (*Channel) Reset

func (c *Channel) Reset()

Reset clears all channel state

func (*Channel) Send

func (c *Channel) Send(data []byte, mode DeliveryMode) uint32

Send queues data for sending with the specified delivery mode. Returns the sequence number assigned to this message.

func (*Channel) SendWithDefault

func (c *Channel) SendWithDefault(data []byte) uint32

SendWithDefault queues data using the channel's default delivery mode

func (*Channel) SetDefaultMode

func (c *Channel) SetDefaultMode(mode DeliveryMode)

SetDefaultMode sets the default delivery mode for this channel

func (*Channel) Stats

func (c *Channel) Stats() ChannelStats

Stats returns a copy of the channel statistics

type ChannelStats

type ChannelStats struct {
	PacketsSent    uint64
	PacketsRecv    uint64
	BytesSent      uint64
	BytesRecv      uint64
	Retransmits    uint64
	PacketsDropped uint64
	FragmentsSent  uint64
	FragmentsRecv  uint64
}

ChannelStats holds per-channel statistics

type CipherType

type CipherType uint8

CipherType identifies the encryption algorithm

const (
	// CipherNone disables encryption
	CipherNone CipherType = iota

	// CipherAESGCM uses AES-256-GCM (authenticated encryption)
	CipherAESGCM

	// CipherChaCha20Poly1305 uses ChaCha20-Poly1305 (authenticated encryption)
	CipherChaCha20Poly1305

	// CipherXChaCha20Poly1305 uses XChaCha20-Poly1305 (extended nonce)
	CipherXChaCha20Poly1305

	// CipherSalsa20 uses Salsa20 (stream cipher, no authentication)
	CipherSalsa20

	// CipherAESCFB uses AES-256-CFB (stream cipher, no authentication)
	CipherAESCFB
)

type Config

type Config struct {
	// MTU is the maximum transmission unit (default: 1400)
	MTU int

	// SendWindow is the send window size in segments (default: 32)
	SendWindow int

	// RecvWindow is the receive window size in segments (default: 128)
	RecvWindow int

	// Interval is the update interval (default: 100ms)
	Interval time.Duration

	// Timeout is the connection timeout (default: 30s)
	Timeout time.Duration

	// KeepAlive is the keep-alive interval (default: 10s)
	KeepAlive time.Duration

	// NoDelay enables no-delay mode for lower latency
	NoDelay bool

	// FastResend triggers fast retransmit after N duplicate ACKs (default: 0, disabled)
	FastResend uint32

	// NoCongestion disables congestion control (for real-time data)
	NoCongestion bool

	// MinRTO is the minimum retransmission timeout (default: 100ms, nodelay: 30ms)
	MinRTO time.Duration

	// Channels is the number of channels (default: 1, max: 256)
	Channels int

	// FEC configuration (Forward Error Correction)
	FEC *FECConfig

	// Crypt configuration (Encryption)
	Crypt *CryptConfig

	// RateLimit is the maximum send rate in bytes per second (0 = unlimited)
	RateLimit int64

	// ReadBufferSize is the socket read buffer size (0 = system default)
	ReadBufferSize int

	// WriteBufferSize is the socket write buffer size (0 = system default)
	WriteBufferSize int

	// DSCP is the Differentiated Services Code Point for QoS (0 = default)
	DSCP int
}

Config holds connection configuration options

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns a Config with default values

func NoDelayConfig

func NoDelayConfig() *Config

NoDelayConfig returns a Config optimized for low latency

type ConfigBuilder

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

ConfigBuilder provides a fluent interface for configuration

func NewConfig

func NewConfig() *ConfigBuilder

NewConfig starts building a new configuration

func (*ConfigBuilder) Build

func (b *ConfigBuilder) Build() *Config

Build returns the final configuration

func (*ConfigBuilder) Channels

func (b *ConfigBuilder) Channels(n int) *ConfigBuilder

Channels sets the number of channels

func (*ConfigBuilder) DSCP

func (b *ConfigBuilder) DSCP(dscp int) *ConfigBuilder

DSCP sets the Differentiated Services Code Point for QoS. Common values: 0 (default), 46 (EF - Expedited Forwarding for VoIP/gaming)

func (*ConfigBuilder) Dial

func (b *ConfigBuilder) Dial(address string) (*Connection, error)

Dial creates a connection using this configuration

func (*ConfigBuilder) Encrypt

func (b *ConfigBuilder) Encrypt(cipher CipherType, key []byte) *ConfigBuilder

Encrypt enables encryption with the specified cipher and key. Supported ciphers: CipherAESGCM, CipherChaCha20Poly1305, CipherXChaCha20Poly1305 Key should be 32 bytes for full security.

func (*ConfigBuilder) EncryptWithPassword

func (b *ConfigBuilder) EncryptWithPassword(cipher CipherType, password string, salt []byte) *ConfigBuilder

EncryptWithPassword derives a key from password and enables encryption. Uses PBKDF2 with SHA-256 for key derivation.

func (*ConfigBuilder) FEC

func (b *ConfigBuilder) FEC(dataShards, parityShards int) *ConfigBuilder

FEC enables Forward Error Correction with the specified data and parity shards. dataShards: number of data packets per FEC group parityShards: number of parity packets (can recover this many lost packets) Example: FEC(10, 3) means 10 data + 3 parity, can recover up to 3 lost packets

func (*ConfigBuilder) Fast

func (b *ConfigBuilder) Fast() *ConfigBuilder

Fast enables low-latency mode

func (*ConfigBuilder) FastRecovery

func (b *ConfigBuilder) FastRecovery() *ConfigBuilder

FastRecovery enables fast recovery settings optimized for lossy networks. This combines FEC, fast retransmit, and no congestion control.

func (*ConfigBuilder) KeepAlive

func (b *ConfigBuilder) KeepAlive(d time.Duration) *ConfigBuilder

KeepAlive sets the keep-alive interval

func (*ConfigBuilder) Listen

func (b *ConfigBuilder) Listen(address string) (*Listener, error)

Listen creates a listener using this configuration

func (*ConfigBuilder) MTU

func (b *ConfigBuilder) MTU(mtu int) *ConfigBuilder

MTU sets the maximum transmission unit

func (*ConfigBuilder) NoCongestion

func (b *ConfigBuilder) NoCongestion() *ConfigBuilder

NoCongestion disables congestion control

func (*ConfigBuilder) RateLimit

func (b *ConfigBuilder) RateLimit(bytesPerSecond int64) *ConfigBuilder

RateLimit sets the maximum send rate in bytes per second. Use 0 for unlimited (default).

func (*ConfigBuilder) Secure

func (b *ConfigBuilder) Secure(key []byte) *ConfigBuilder

Secure enables AES-GCM encryption with the provided key. This is a convenience method for the most common secure configuration.

func (*ConfigBuilder) SecureWithPassword

func (b *ConfigBuilder) SecureWithPassword(password string, salt []byte) *ConfigBuilder

SecureWithPassword enables AES-GCM encryption with a password-derived key.

func (*ConfigBuilder) SocketBuffers

func (b *ConfigBuilder) SocketBuffers(readSize, writeSize int) *ConfigBuilder

SocketBuffers sets the socket read and write buffer sizes. Use 0 for system default.

func (*ConfigBuilder) Timeout

func (b *ConfigBuilder) Timeout(d time.Duration) *ConfigBuilder

Timeout sets the connection timeout

func (*ConfigBuilder) Window

func (b *ConfigBuilder) Window(send, recv int) *ConfigBuilder

Window sets send and receive window sizes

type CongestionController

type CongestionController interface {
	// OnACK is called when an ACK is received
	OnACK(acked uint32)

	// OnLoss is called when packet loss is detected (fast retransmit)
	OnLoss()

	// OnTimeout is called when a timeout occurs
	OnTimeout()

	// WindowSize returns the current congestion window size
	WindowSize() uint32

	// CanSend returns true if we can send more packets
	CanSend(inFlight uint32) bool

	// SetRemoteWindow sets the remote advertised window
	SetRemoteWindow(wnd uint32)

	// Reset resets the congestion controller state
	Reset()
}

CongestionController interface for pluggable congestion control algorithms

type CongestionStats

type CongestionStats struct {
	CWND      uint32
	SSThresh  uint32
	RemoteWnd uint32
	SendWnd   uint32
	NoCwnd    bool
}

CongestionStats contains congestion control statistics

type Conn

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

Conn wraps a Connection with io.ReadWriteCloser interface.

func NewConn

func NewConn(c *Connection) *Conn

NewConn wraps a Connection with simplified read/write methods

func (*Conn) Read

func (c *Conn) Read(p []byte) (n int, err error)

Read implements io.Reader - receives data from any channel

func (*Conn) SetChannel

func (c *Conn) SetChannel(ch uint8) *Conn

SetChannel sets the default channel for Write operations

func (*Conn) SetMode

func (c *Conn) SetMode(mode DeliveryMode) *Conn

SetMode sets the default delivery mode for Write operations

func (*Conn) Write

func (c *Conn) Write(p []byte) (n int, err error)

Write implements io.Writer - sends data reliably on default channel

type ConnectOptions

type ConnectOptions struct {
	// Config is the connection configuration
	Config *Config

	// LocalAddr is the local address to bind to (optional)
	LocalAddr string

	// Timeout is the connection timeout
	Timeout time.Duration
}

ConnectOptions holds options for Dial

type Connection

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

Connection represents a bidirectional FDP connection to a remote peer.

func Connect

func Connect(address string) (*Connection, error)

Connect is an alias for Dial with simpler error handling

func ConnectFast

func ConnectFast(address string) (*Connection, error)

ConnectFast connects with low-latency settings

func ConnectWithTimeout

func ConnectWithTimeout(address string, timeout time.Duration) (*Connection, error)

ConnectWithTimeout connects with a custom timeout

func Dial

func Dial(network, address string) (*Connection, error)

Dial creates a new FDP connection to the specified address.

func DialConfig

func DialConfig(network, address string, config *Config) (*Connection, error)

DialConfig creates a new FDP connection with custom configuration.

func DialWithOptions

func DialWithOptions(network, address string, opts *ConnectOptions) (*Connection, error)

DialWithOptions creates a new FDP connection with detailed options.

func NewConnection

func NewConnection(id uint32, remoteAddr net.Addr, config *Config) *Connection

NewConnection creates a new FDP connection

func (*Connection) Close

func (c *Connection) Close() error

Close closes the connection

func (*Connection) ID

func (c *Connection) ID() uint32

ID returns the connection identifier

func (*Connection) Input

func (c *Connection) Input(data []byte) error

Input processes an incoming packet. This should be called by the transport layer when a packet is received.

func (*Connection) IsConnected

func (c *Connection) IsConnected() bool

IsConnected returns true if the connection is established

func (*Connection) LastError

func (c *Connection) LastError() error

LastError returns the last error

func (*Connection) LocalAddr

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

LocalAddr returns the local network address

func (*Connection) Recv

func (c *Connection) Recv() (uint8, []byte, error)

Recv receives data from any channel. Returns the channel ID, data, and any error. Blocks until data is available or the connection is closed.

func (*Connection) RecvData

func (c *Connection) RecvData() ([]byte, error)

RecvData receives data, discarding channel information

func (*Connection) RecvFrom

func (c *Connection) RecvFrom() (channel uint8, data []byte, err error)

RecvFrom receives data and returns it along with the channel

func (*Connection) RecvTimeout

func (c *Connection) RecvTimeout(timeout time.Duration) (uint8, []byte, error)

RecvTimeout is like Recv but with a timeout.

func (*Connection) RemoteAddr

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

RemoteAddr returns the remote network address

func (*Connection) Send

func (c *Connection) Send(channel uint8, data []byte, mode DeliveryMode) error

Send queues data for sending on the specified channel with the given delivery mode. Returns an error if the connection is closed or the buffer is full.

func (*Connection) SendFast

func (c *Connection) SendFast(data []byte) error

SendFast sends data reliably but without ordering on channel 0

func (*Connection) SendOn

func (c *Connection) SendOn(channel uint8, data []byte) error

SendOn sends data on a specific channel with reliable ordered delivery

func (*Connection) SendReliable

func (c *Connection) SendReliable(data []byte) error

SendReliable sends data reliably and in order on channel 0

func (*Connection) SendStream

func (c *Connection) SendStream(data []byte) error

SendStream sends data unreliably but ordered (for streaming) on channel 0

func (*Connection) SendUnreliable

func (c *Connection) SendUnreliable(data []byte) error

SendUnreliable sends data without reliability guarantees on channel 0

func (*Connection) SetDeadline

func (c *Connection) SetDeadline(t time.Time) error

SetDeadline sets the read and write deadlines

func (*Connection) SetOutput

func (c *Connection) SetOutput(output OutputCallback)

SetOutput sets the output callback for sending packets

func (*Connection) SetReadDeadline

func (c *Connection) SetReadDeadline(t time.Time) error

SetReadDeadline sets the deadline for future Read calls

func (*Connection) SetState

func (c *Connection) SetState(state ConnectionState)

SetState sets the connection state

func (*Connection) SetWriteDeadline

func (c *Connection) SetWriteDeadline(t time.Time) error

SetWriteDeadline sets the deadline for future Write calls

func (*Connection) State

func (c *Connection) State() ConnectionState

State returns the current connection state

func (*Connection) Stats

func (c *Connection) Stats() ConnectionStats

Stats returns current connection statistics

func (*Connection) TryRecv

func (c *Connection) TryRecv() (uint8, []byte, error)

TryRecv attempts to receive data without blocking. Returns nil, nil, nil if no data is available.

func (*Connection) Update

func (c *Connection) Update()

Update processes pending operations. This should be called periodically (e.g., every 10-100ms).

type ConnectionState

type ConnectionState uint32

ConnectionState represents the state of a connection

const (
	StateDisconnected ConnectionState = iota
	StateConnecting
	StateConnected
	StateDisconnecting
)

func (ConnectionState) String

func (s ConnectionState) String() string

type ConnectionStats

type ConnectionStats struct {
	// Packets
	PacketsSent    uint64
	PacketsRecv    uint64
	PacketsLost    uint64
	PacketsRetrans uint64

	// Bytes
	BytesSent uint64
	BytesRecv uint64

	// Timing
	RTT    time.Duration
	RTTVar time.Duration
	RTO    time.Duration

	// Window
	SendWindow       uint32
	RecvWindow       uint32
	CongestionWindow uint32

	// Connection
	State  ConnectionState
	Uptime time.Duration
}

ConnectionStats holds connection statistics

type CounterNonce

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

CounterNonce generates nonces using a counter (faster than random).

func NewCounterNonce

func NewCounterNonce() (*CounterNonce, error)

NewCounterNonce creates a new counter-based nonce generator

func (*CounterNonce) Counter

func (c *CounterNonce) Counter() uint64

Counter returns the current counter value

func (*CounterNonce) Next

func (c *CounterNonce) Next() []byte

Next returns the next nonce (12 bytes: 8 prefix + 4 counter)

func (*CounterNonce) NextInto

func (c *CounterNonce) NextInto(nonce []byte)

NextInto fills the provided buffer with the next nonce

type CryptConfig

type CryptConfig struct {
	Cipher  CipherType // Encryption algorithm
	Key     []byte     // Encryption key (32 bytes for full security)
	Enabled bool       // Whether encryption is active
}

CryptConfig configures packet encryption.

func DefaultCryptConfig

func DefaultCryptConfig() *CryptConfig

DefaultCryptConfig returns disabled encryption configuration

type DeliveryMode

type DeliveryMode uint8

DeliveryMode specifies how packets should be delivered

const (
	// ReliableOrdered guarantees delivery and ordering (like TCP)
	ReliableOrdered DeliveryMode = iota
	// ReliableUnordered guarantees delivery but may arrive out of order
	ReliableUnordered
	// UnreliableOrdered may be dropped but maintains order (drops old packets)
	UnreliableOrdered
	// UnreliableUnordered is fire-and-forget with no guarantees
	UnreliableUnordered
)

type Entropy

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

Entropy provides fast, cryptographically secure random bytes using AES-CTR.

func GetEntropy

func GetEntropy() *Entropy

GetEntropy returns the global entropy source

func NewEntropy

func NewEntropy() *Entropy

NewEntropy creates a new entropy source

func (*Entropy) Fill

func (e *Entropy) Fill(buf []byte) error

Fill fills the buffer with random bytes

func (*Entropy) Uint32

func (e *Entropy) Uint32() uint32

Uint32 returns a random uint32

func (*Entropy) Uint64

func (e *Entropy) Uint64() uint64

Uint64 returns a random uint64

type FECConfig

type FECConfig struct {
	DataShards   int  // Number of data shards (K)
	ParityShards int  // Number of parity shards (M), can recover M losses
	Enabled      bool // Whether FEC is active
}

FECConfig configures Forward Error Correction.

func DefaultFECConfig

func DefaultFECConfig() *FECConfig

DefaultFECConfig returns the default FEC configuration

type FECDecoder

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

FECDecoder handles FEC decoding for incoming packets.

func NewFECDecoder

func NewFECDecoder(config *FECConfig) (*FECDecoder, error)

NewFECDecoder creates a new FEC decoder

func (*FECDecoder) Cleanup

func (d *FECDecoder) Cleanup(maxAge uint32, currentTime uint32)

Cleanup removes old FEC groups that haven't been completed

func (*FECDecoder) Decode

func (d *FECDecoder) Decode(shards [][]byte) ([][]byte, error)

Decode attempts to recover lost shards from received shards. Shards should include FEC headers. Returns recovered data shards.

func (*FECDecoder) DecodeGroup

func (d *FECDecoder) DecodeGroup(seqID uint16) ([][]byte, error)

DecodeGroup decodes a group identified by sequence ID. Call Input to add shards, then DecodeGroup when ready.

func (*FECDecoder) Input

func (d *FECDecoder) Input(shard []byte) (seqID uint16, ready bool)

Input adds a shard to the decoder's buffer. Returns true if the group is ready for decoding.

type FECEncoder

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

FECEncoder handles FEC encoding for outgoing packets

func NewFECEncoder

func NewFECEncoder(config *FECConfig) (*FECEncoder, error)

NewFECEncoder creates a new FEC encoder

func (*FECEncoder) Encode

func (e *FECEncoder) Encode(data [][]byte) ([][]byte, error)

Encode takes data shards and generates parity shards. Returns all shards (data + parity) with FEC headers prepended.

func (*FECEncoder) EncodeSingle

func (e *FECEncoder) EncodeSingle(data []byte) [][]byte

EncodeSingle encodes a single packet, buffering until a full group is ready. Returns encoded shards when a complete group is formed, nil otherwise.

type FragmentAssembly

type FragmentAssembly struct {
	Sequence  uint32
	Total     uint8
	Received  uint8
	Fragments [][]byte
	Timestamp uint32
}

FragmentAssembly tracks fragments for reassembly

func AcquireFragmentAssembly

func AcquireFragmentAssembly() *FragmentAssembly

AcquireFragmentAssembly gets a FragmentAssembly from the pool.

type KCPCongestion

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

KCPCongestion implements KCP-style congestion control. It supports optional bypass of congestion control for real-time applications.

func NewKCPCongestion

func NewKCPCongestion(sendWnd, mss uint32) *KCPCongestion

NewKCPCongestion creates a new KCP-style congestion controller

func (*KCPCongestion) CanSend

func (c *KCPCongestion) CanSend(inFlight uint32) bool

CanSend returns true if we can send more packets

func (*KCPCongestion) OnACK

func (c *KCPCongestion) OnACK(acked uint32)

OnACK is called when an ACK is received

func (*KCPCongestion) OnLoss

func (c *KCPCongestion) OnLoss()

OnLoss is called when packet loss is detected (fast retransmit)

func (*KCPCongestion) OnTimeout

func (c *KCPCongestion) OnTimeout()

OnTimeout is called when a timeout occurs

func (*KCPCongestion) Reset

func (c *KCPCongestion) Reset()

Reset resets the congestion controller state

func (*KCPCongestion) SetNoCongestion

func (c *KCPCongestion) SetNoCongestion(enabled bool)

SetNoCongestion enables or disables congestion control bypass. When enabled, only send window and remote window limit transmission.

func (*KCPCongestion) SetRemoteWindow

func (c *KCPCongestion) SetRemoteWindow(wnd uint32)

SetRemoteWindow sets the remote advertised window

func (*KCPCongestion) Stats

func (c *KCPCongestion) Stats() CongestionStats

Stats returns congestion control statistics

func (*KCPCongestion) WindowSize

func (c *KCPCongestion) WindowSize() uint32

WindowSize returns the current effective window size

type Listener

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

Listener accepts incoming FDP connections

func Listen

func Listen(network, address string) (*Listener, error)

Listen creates a new FDP listener on the specified network address. Network should be "udp", "udp4", or "udp6".

func ListenConfig

func ListenConfig(network, address string, config *Config) (*Listener, error)

ListenConfig creates a new FDP listener with custom configuration.

func (*Listener) Accept

func (l *Listener) Accept() (*Connection, error)

Accept waits for and returns the next connection to the listener.

func (*Listener) Addr

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

Addr returns the listener's network address.

func (*Listener) Close

func (l *Listener) Close() error

Close closes the listener.

type Message

type Message struct {
	Data []byte
	Addr net.Addr
}

Message represents a single packet for batch operations

type NoCongestion

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

NoCongestion is a no-op congestion controller for maximum throughput. It only respects send window and remote window limits.

func NewNoCongestion

func NewNoCongestion(sendWnd uint32) *NoCongestion

NewNoCongestion creates a congestion controller that does nothing

func (*NoCongestion) CanSend

func (c *NoCongestion) CanSend(inFlight uint32) bool

func (*NoCongestion) OnACK

func (c *NoCongestion) OnACK(acked uint32)

func (*NoCongestion) OnLoss

func (c *NoCongestion) OnLoss()

func (*NoCongestion) OnTimeout

func (c *NoCongestion) OnTimeout()

func (*NoCongestion) Reset

func (c *NoCongestion) Reset()

func (*NoCongestion) SetRemoteWindow

func (c *NoCongestion) SetRemoteWindow(wnd uint32)

func (*NoCongestion) WindowSize

func (c *NoCongestion) WindowSize() uint32

type NoncePool

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

NoncePool provides pooled nonce generation.

func NewNoncePool

func NewNoncePool(nonceSize int) *NoncePool

NewNoncePool creates a nonce pool for the given nonce size

func (*NoncePool) Get

func (p *NoncePool) Get() []byte

Get returns a fresh nonce from the pool

func (*NoncePool) Put

func (p *NoncePool) Put(nonce []byte)

Put returns a nonce to the pool

type OutputCallback

type OutputCallback func(data []byte, addr net.Addr) error

OutputCallback is called to send a packet

type Packet

type Packet struct {
	// Connection ID (32-bit) - identifies the connection
	ConnID uint32

	// Flags (8-bit) - packet type and flags
	Flags uint8

	// Timestamp (32-bit) - sender's timestamp for RTT calculation
	Timestamp uint32

	// Sequence (32-bit) - packet sequence number
	Sequence uint32

	// Una (32-bit) - unacknowledged sequence number (cumulative ACK)
	Una uint32

	// Window (16-bit) - receiver window size
	Window uint16

	// Length (16-bit) - payload length
	Length uint16

	// Channel (8-bit) - channel ID (0-255)
	Channel uint8

	// Fragment (8-bit) - fragment info (0 = no fragment, >0 = fragments remaining)
	Fragment uint8

	// Data is the packet payload
	Data []byte
}

Packet represents an FDP network packet.

Header layout (20 bytes):

0               4               8 (BYTE)
+---------------+---------------+
|  connection   |    flags      |
+---------------+---------------+   4
|   timestamp   |  sequence     |
+---------------+---------------+  12
|      una      |    window     |
+---------------+-------+-------+  20
|     length    | chan  | frag  |
+---------------+-------+-------+
|        DATA (optional)        |
+-------------------------------+

func AcquirePacket

func AcquirePacket() *Packet

AcquirePacket gets a Packet from the pool. The returned packet is reset and ready for use.

func (*Packet) Decode

func (p *Packet) Decode(buf []byte) error

Decode deserializes a packet from the provided buffer. Returns an error if the buffer is too small or contains invalid data.

func (*Packet) Encode

func (p *Packet) Encode(buf []byte) (int, error)

Encode serializes the packet into the provided buffer. Returns the number of bytes written or an error. The buffer must be at least HeaderSize + len(p.Data) bytes.

func (*Packet) EncodeHeader

func (p *Packet) EncodeHeader(buf []byte) error

EncodeHeader writes only the header portion to the buffer. This is useful when building packets with scatter-gather I/O.

func (*Packet) IsACK

func (p *Packet) IsACK() bool

IsACK returns true if the packet is an acknowledgment

func (*Packet) IsConnect

func (p *Packet) IsConnect() bool

IsConnect returns true if the packet is a connection control packet

func (*Packet) IsFragment

func (p *Packet) IsFragment() bool

IsFragment returns true if the packet is a fragment

func (*Packet) IsOrdered

func (p *Packet) IsOrdered() bool

IsOrdered returns true if the packet must be delivered in order

func (*Packet) IsReliable

func (p *Packet) IsReliable() bool

IsReliable returns true if the packet requires acknowledgment

func (*Packet) Reset

func (p *Packet) Reset()

Reset clears the packet for reuse

func (*Packet) Size

func (p *Packet) Size() int

Size returns the total packet size including header

type PoolStats

type PoolStats struct {
	PacketsAcquired  uint64
	PacketsReleased  uint64
	SegmentsAcquired uint64
	SegmentsReleased uint64
	BuffersAcquired  uint64
	BuffersReleased  uint64
}

PoolStats holds statistics about pool usage

func GetPoolStats

func GetPoolStats() PoolStats

GetPoolStats returns current pool statistics. This is mainly useful for debugging and monitoring.

type RTTEstimator

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

RTTEstimator estimates round-trip time and calculates retransmission timeouts. It uses the Jacobson/Karels algorithm with modifications from KCP.

func NewRTTEstimator

func NewRTTEstimator() *RTTEstimator

NewRTTEstimator creates a new RTT estimator

func (*RTTEstimator) CalculateBackoff

func (r *RTTEstimator) CalculateBackoff(baseRTO int32, transmits uint32) int32

CalculateBackoff calculates the RTO for a retransmission. transmits is the number of times the segment has been transmitted.

func (*RTTEstimator) RTO

func (r *RTTEstimator) RTO() int32

RTO returns the current retransmission timeout in milliseconds

func (*RTTEstimator) RTTVAR

func (r *RTTEstimator) RTTVAR() int32

RTTVAR returns the RTT variance in milliseconds

func (*RTTEstimator) SRTT

func (r *RTTEstimator) SRTT() int32

SRTT returns the smoothed RTT in milliseconds

func (*RTTEstimator) SetInterval

func (r *RTTEstimator) SetInterval(interval int32)

SetInterval sets the timer interval for RTO calculation

func (*RTTEstimator) SetMinRTO

func (r *RTTEstimator) SetMinRTO(minRTO int32)

SetMinRTO sets the minimum RTO

func (*RTTEstimator) SetNoDelay

func (r *RTTEstimator) SetNoDelay(enabled bool)

SetNoDelay enables or disables no-delay mode. In no-delay mode, RTO multiplier is 1.5x and minimum RTO is 30ms.

func (*RTTEstimator) Stats

func (r *RTTEstimator) Stats() RTTStats

Stats returns RTT statistics

func (*RTTEstimator) Update

func (r *RTTEstimator) Update(rtt int32)

Update updates the RTT estimator with a new sample. rtt is the measured round-trip time in milliseconds.

type RTTStats

type RTTStats struct {
	SRTT     int32  // Smoothed RTT
	RTTVAR   int32  // RTT variance
	RTO      int32  // Current RTO
	MinRTT   int32  // Minimum observed RTT
	MaxRTT   int32  // Maximum observed RTT
	AvgRTT   int32  // Average RTT
	LastRTT  int32  // Last RTT sample
	Samples  uint64 // Number of samples
	NoDelay  bool   // Whether no-delay mode is enabled
	Interval int32  // Timer interval
}

RTTStats contains RTT statistics

type RateLimiter

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

RateLimiter implements token bucket rate limiting.

func NewRateLimiter

func NewRateLimiter(rate, burst int64) *RateLimiter

NewRateLimiter creates a rate limiter. Rate is bytes/sec (0 = unlimited).

func (*RateLimiter) Allow

func (r *RateLimiter) Allow(n int) bool

Allow checks if n bytes can be sent and consumes tokens. Returns true if allowed, false if rate limited.

func (*RateLimiter) Rate

func (r *RateLimiter) Rate() int64

Rate returns the current rate limit

func (*RateLimiter) Reset

func (r *RateLimiter) Reset()

Reset resets the rate limiter to full capacity

func (*RateLimiter) SetBurst

func (r *RateLimiter) SetBurst(burst int64)

SetBurst updates the burst capacity

func (*RateLimiter) SetRate

func (r *RateLimiter) SetRate(rate int64)

SetRate updates the rate limit (bytes per second)

func (*RateLimiter) Stats

func (r *RateLimiter) Stats() (throttledBytes, throttledCount uint64)

Stats returns rate limiting statistics

func (*RateLimiter) Tokens

func (r *RateLimiter) Tokens() int64

Tokens returns the current available tokens (in bytes)

func (*RateLimiter) Wait

func (r *RateLimiter) Wait(n int)

Wait blocks until n bytes can be sent. Returns immediately if rate is unlimited.

func (*RateLimiter) WaitContext

func (r *RateLimiter) WaitContext(n int, deadline time.Time) bool

WaitContext waits with a deadline, returns false if deadline exceeded

type RecvBuffer

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

RecvBuffer manages received segments and handles reordering.

func NewRecvBuffer

func NewRecvBuffer(window ...uint32) *RecvBuffer

NewRecvBuffer creates a new receive buffer

func (*RecvBuffer) Clear

func (b *RecvBuffer) Clear()

Clear removes all segments from the buffer

func (*RecvBuffer) Insert

func (b *RecvBuffer) Insert(seg *Segment) bool

Insert adds a segment to the receive buffer. Returns true if the segment was accepted, false if it's a duplicate or out of window.

func (*RecvBuffer) NextSeq

func (b *RecvBuffer) NextSeq() uint32

NextSeq returns the next expected sequence number

func (*RecvBuffer) ReadReady

func (b *RecvBuffer) ReadReady() []*Segment

ReadReady returns segments that are ready for delivery (in order).

func (*RecvBuffer) Remove

func (b *RecvBuffer) Remove(seq uint32) *Segment

Remove removes and returns a segment by sequence number

func (*RecvBuffer) SetNextSeq

func (b *RecvBuffer) SetNextSeq(seq uint32)

SetNextSeq sets the next expected sequence number

func (*RecvBuffer) WindowSize

func (b *RecvBuffer) WindowSize() uint32

WindowSize returns the current receive window size

type RecvHeap

type RecvHeap []*Segment

RecvHeap is a min-heap of segments ordered by sequence number. Used for reassembling out-of-order packets.

func (RecvHeap) Len

func (h RecvHeap) Len() int

func (RecvHeap) Less

func (h RecvHeap) Less(i, j int) bool

func (*RecvHeap) Pop

func (h *RecvHeap) Pop() interface{}

func (*RecvHeap) Push

func (h *RecvHeap) Push(x interface{})

func (RecvHeap) Swap

func (h RecvHeap) Swap(i, j int)

type Segment

type Segment struct {
	// Sequence number of this segment
	Sequence uint32

	// Timestamp when segment was first sent
	Timestamp uint32

	// Retransmission timeout for this segment
	RTO uint32

	// Time when segment should be retransmitted
	ResendTS uint32

	// Number of times segment has been transmitted
	Transmits uint32

	// Fast ACK count (for fast retransmit)
	FastACK uint32

	// Channel ID
	Channel uint8

	// Fragment index (0 = not fragmented, or fragment number)
	Fragment uint8

	// Total fragment count (for reassembly)
	FragmentCount uint8

	// Flags for this segment
	Flags uint8

	// Payload data
	Data []byte
	// contains filtered or unexported fields
}

Segment represents a message segment in the send/receive queues. This is the internal representation used for retransmission and ordering.

func AcquireSegment

func AcquireSegment() *Segment

AcquireSegment gets a Segment from the pool. The returned segment is reset and ready for use.

func (*Segment) IsReliable

func (s *Segment) IsReliable() bool

IsReliable returns true if this segment requires acknowledgment

func (*Segment) NeedsResend

func (s *Segment) NeedsResend(currentTime uint32) bool

NeedsResend returns true if the segment needs to be retransmitted

func (*Segment) Reset

func (s *Segment) Reset()

Reset clears the segment for reuse

type SegmentQueue

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

SegmentQueue is a thread-safe queue for segments. Used for send buffer, receive buffer, and ACK list.

func NewSegmentQueue

func NewSegmentQueue(capacity ...int) *SegmentQueue

NewSegmentQueue creates a new segment queue with initial capacity

func (*SegmentQueue) Clear

func (q *SegmentQueue) Clear()

Clear removes all segments from the queue

func (*SegmentQueue) Find

func (q *SegmentQueue) Find(seq uint32) *Segment

Find returns a segment by sequence number without removing it

func (*SegmentQueue) ForEach

func (q *SegmentQueue) ForEach(fn func(*Segment) bool)

ForEach iterates over all segments

func (*SegmentQueue) Len

func (q *SegmentQueue) Len() int

Len returns the number of segments in the queue

func (*SegmentQueue) Peek

func (q *SegmentQueue) Peek() *Segment

Peek returns the first segment without removing it

func (*SegmentQueue) Pop

func (q *SegmentQueue) Pop() *Segment

Pop removes and returns the first segment, or nil if empty

func (*SegmentQueue) Push

func (q *SegmentQueue) Push(seg *Segment)

Push adds a segment to the queue

func (*SegmentQueue) Remove

func (q *SegmentQueue) Remove(seq uint32) *Segment

Remove removes a segment by sequence number Returns the removed segment or nil if not found

func (*SegmentQueue) RemoveUntil

func (q *SegmentQueue) RemoveUntil(seq uint32) []*Segment

RemoveUntil removes all segments with sequence numbers less than seq Returns the removed segments

type SendBuffer

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

SendBuffer manages segments awaiting acknowledgment. Organized for efficient timeout checking and ACK processing.

func NewSendBuffer

func NewSendBuffer() *SendBuffer

NewSendBuffer creates a new send buffer

func (*SendBuffer) AckUntil

func (b *SendBuffer) AckUntil(una uint32) []*Segment

AckUntil acknowledges all segments up to (but not including) una. Returns the acknowledged segments.

func (*SendBuffer) Add

func (b *SendBuffer) Add(seg *Segment)

Add adds a segment to the send buffer

func (*SendBuffer) Clear

func (b *SendBuffer) Clear()

Clear removes all segments from the buffer

func (*SendBuffer) ForEach

func (b *SendBuffer) ForEach(fn func(*Segment) bool)

ForEach iterates over all segments in the buffer

func (*SendBuffer) Get

func (b *SendBuffer) Get(seq uint32) *Segment

Get returns a segment by sequence number without removing it

func (*SendBuffer) GetTimeouts

func (b *SendBuffer) GetTimeouts(currentTime uint32) []*Segment

GetTimeouts returns all segments that need retransmission

func (*SendBuffer) IncrementFastACK

func (b *SendBuffer) IncrementFastACK(maxACK uint32, threshold uint32) []*Segment

IncrementFastACK increments the fast ACK counter for segments with sequence numbers less than maxACK. Returns segments that should be fast retransmitted.

func (*SendBuffer) Insert

func (b *SendBuffer) Insert(seg *Segment)

Insert is an alias for Add

func (*SendBuffer) Len

func (b *SendBuffer) Len() int

Len returns the number of segments in the buffer

func (*SendBuffer) Remove

func (b *SendBuffer) Remove(seq uint32) *Segment

Remove removes and returns a segment by sequence number

func (*SendBuffer) RemoveUntil

func (b *SendBuffer) RemoveUntil(seq uint32) []*Segment

RemoveUntil removes all segments with sequence numbers less than seq Returns the removed segments

type SlidingWindowCounter

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

SlidingWindowCounter limits events per time window.

func NewSlidingWindowCounter

func NewSlidingWindowCounter(limit int64, window time.Duration) *SlidingWindowCounter

NewSlidingWindowCounter creates a sliding window rate counter

func (*SlidingWindowCounter) Allow

func (s *SlidingWindowCounter) Allow() bool

Allow checks if an event is allowed under the rate limit

func (*SlidingWindowCounter) Count

func (s *SlidingWindowCounter) Count() int64

Count returns the current count in the window

type Stats

type Stats struct {
	// Connection stats
	ActiveOpens  uint64
	PassiveOpens uint64
	AttemptFails uint64
	EstabResets  uint64
	CurrEstab    uint64
	MaxConn      uint64

	// Input stats
	InSegs      uint64
	InBytes     uint64
	InPkts      uint64
	InErrs      uint64
	InCsumErrs  uint64
	InOrderSegs uint64
	InDupSegs   uint64
	InOOOSegs   uint64

	// Output stats
	OutSegs  uint64
	OutBytes uint64
	OutPkts  uint64

	// Retransmission stats
	RetransSegs      uint64
	FastRetransSegs  uint64
	EarlyRetransSegs uint64
	LostSegs         uint64
	RepeatSegs       uint64

	// FEC stats
	FECRecovered    uint64
	FECParityShards uint64
	FECShardErrs    uint64

	// Encryption stats
	EncryptedPkts uint64
	DecryptedPkts uint64
	CryptErrs     uint64

	// Rate limiting stats
	ThrottledBytes uint64
	ThrottledPkts  uint64

	// RTT stats (microseconds)
	RTTMin   uint64
	RTTMax   uint64
	RTTSum   uint64
	RTTCount uint64
}

Stats holds FDP statistics (SNMP-style counters).

func DefaultStats

func DefaultStats() *Stats

DefaultStats returns the global statistics.

func (*Stats) AddCurrEstab

func (s *Stats) AddCurrEstab(delta int64)

AddCurrEstab adds to current connections

func (*Stats) AddFECParityShards

func (s *Stats) AddFECParityShards(n uint64)

AddFECParityShards adds FEC parity shards count

func (*Stats) AddInBytes

func (s *Stats) AddInBytes(n uint64)

AddInBytes adds to received bytes

func (*Stats) AddOutBytes

func (s *Stats) AddOutBytes(n uint64)

AddOutBytes adds to sent bytes

func (*Stats) AddThrottledBytes

func (s *Stats) AddThrottledBytes(n uint64)

AddThrottledBytes adds throttled bytes

func (*Stats) Copy

func (s *Stats) Copy() Stats

Copy creates a snapshot of the statistics

func (*Stats) GetAvgRTT

func (s *Stats) GetAvgRTT() uint64

GetAvgRTT returns the average RTT in microseconds

func (*Stats) IncrActiveOpens

func (s *Stats) IncrActiveOpens()

IncrActiveOpens increments active connection attempts

func (*Stats) IncrAttemptFails

func (s *Stats) IncrAttemptFails()

IncrAttemptFails increments failed attempts

func (*Stats) IncrCryptErrs

func (s *Stats) IncrCryptErrs()

IncrCryptErrs increments crypto errors

func (*Stats) IncrDecryptedPkts

func (s *Stats) IncrDecryptedPkts()

IncrDecryptedPkts increments decrypted packets

func (*Stats) IncrEarlyRetransSegs

func (s *Stats) IncrEarlyRetransSegs()

IncrEarlyRetransSegs increments early retransmit segments

func (*Stats) IncrEncryptedPkts

func (s *Stats) IncrEncryptedPkts()

IncrEncryptedPkts increments encrypted packets

func (*Stats) IncrEstabResets

func (s *Stats) IncrEstabResets()

IncrEstabResets increments connection resets

func (*Stats) IncrFECRecovered

func (s *Stats) IncrFECRecovered()

IncrFECRecovered increments FEC recovered packets

func (*Stats) IncrFECShardErrs

func (s *Stats) IncrFECShardErrs()

IncrFECShardErrs increments FEC shard errors

func (*Stats) IncrFastRetransSegs

func (s *Stats) IncrFastRetransSegs()

IncrFastRetransSegs increments fast retransmit segments

func (*Stats) IncrInCsumErrs

func (s *Stats) IncrInCsumErrs()

IncrInCsumErrs increments checksum errors

func (*Stats) IncrInDupSegs

func (s *Stats) IncrInDupSegs()

IncrInDupSegs increments duplicate segments

func (*Stats) IncrInErrs

func (s *Stats) IncrInErrs()

IncrInErrs increments input errors

func (*Stats) IncrInOOOSegs

func (s *Stats) IncrInOOOSegs()

IncrInOOOSegs increments out-of-order segments

func (*Stats) IncrInOrderSegs

func (s *Stats) IncrInOrderSegs()

IncrInOrderSegs increments in-order segments

func (*Stats) IncrInPkts

func (s *Stats) IncrInPkts()

IncrInPkts increments received packets

func (*Stats) IncrInSegs

func (s *Stats) IncrInSegs()

IncrInSegs increments received segments

func (*Stats) IncrLostSegs

func (s *Stats) IncrLostSegs()

IncrLostSegs increments lost segments

func (*Stats) IncrOutPkts

func (s *Stats) IncrOutPkts()

IncrOutPkts increments sent packets

func (*Stats) IncrOutSegs

func (s *Stats) IncrOutSegs()

IncrOutSegs increments sent segments

func (*Stats) IncrPassiveOpens

func (s *Stats) IncrPassiveOpens()

IncrPassiveOpens increments passive connections

func (*Stats) IncrRepeatSegs

func (s *Stats) IncrRepeatSegs()

IncrRepeatSegs increments repeated segments

func (*Stats) IncrRetransSegs

func (s *Stats) IncrRetransSegs()

IncrRetransSegs increments retransmitted segments

func (*Stats) IncrThrottledPkts

func (s *Stats) IncrThrottledPkts()

IncrThrottledPkts increments throttled packets

func (*Stats) Reset

func (s *Stats) Reset()

Reset resets all statistics to zero

func (*Stats) SetCurrEstab

func (s *Stats) SetCurrEstab(n uint64)

SetCurrEstab sets current connections (use Add/Sub for inc/dec)

func (*Stats) UpdateRTT

func (s *Stats) UpdateRTT(rttUs uint64)

UpdateRTT updates RTT statistics with a new sample (in microseconds)

type StatsHistory

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

StatsHistory maintains a rolling history for rate calculations

func NewStatsHistory

func NewStatsHistory(interval time.Duration, duration time.Duration) *StatsHistory

NewStatsHistory creates a statistics history

func (*StatsHistory) GetInBytesPerSecond

func (h *StatsHistory) GetInBytesPerSecond() float64

GetInBytesPerSecond returns the incoming bytes per second

func (*StatsHistory) GetOutBytesPerSecond

func (h *StatsHistory) GetOutBytesPerSecond() float64

GetOutBytesPerSecond returns the outgoing bytes per second

func (*StatsHistory) GetPacketsPerSecond

func (h *StatsHistory) GetPacketsPerSecond() float64

GetPacketsPerSecond returns the total packets per second

func (*StatsHistory) GetRate

func (h *StatsHistory) GetRate(getter func(s *Stats) uint64) float64

GetRate calculates the rate (per second) for a specific counter

func (*StatsHistory) GetRetransmitRate

func (h *StatsHistory) GetRetransmitRate() float64

GetRetransmitRate returns the retransmission rate (retrans / total sent)

func (*StatsHistory) Record

func (h *StatsHistory) Record(s *Stats)

Record takes a snapshot of the current statistics

type StatsSnapshot

type StatsSnapshot struct {
	Stats     Stats
	Timestamp time.Time
}

StatsSnapshot is a time-series snapshot for rate calculations

Directories

Path Synopsis
examples
echo/client command
Echo client example for FDP (Fast Datagram Protocol)
Echo client example for FDP (Fast Datagram Protocol)
echo/server command
Echo server example for FDP (Fast Datagram Protocol)
Echo server example for FDP (Fast Datagram Protocol)

Jump to

Keyboard shortcuts

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