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
- Variables
- func AcquireBuffer() []byte
- func AcquireCryptBuffer() []byte
- func AcquireSmallBuffer() []byte
- func DeriveKey(password []byte, salt []byte) []byte
- func EncodeACKPayload(buf []byte, acks []ACKInfo) (int, error)
- func FillRandom(buf []byte) error
- func RandomBytes(n int) []byte
- func RandomUint32() uint32
- func RandomUint64() uint64
- func ReleaseACKInfoSlice(s []ACKInfo)
- func ReleaseBuffer(b []byte)
- func ReleaseCryptBuffer(b []byte)
- func ReleaseFragmentAssembly(f *FragmentAssembly)
- func ReleasePacket(p *Packet)
- func ReleaseSegment(s *Segment)
- func ReleaseSmallBuffer(b []byte)
- func ResetPoolStats()
- func Serve(address string, handler func(*Connection)) error
- func ServeWithConfig(address string, config *Config, handler func(*Connection)) error
- func SetEntropy(reader io.Reader)
- type ACKInfo
- type ACKList
- type ACKRange
- type BandwidthControl
- func (bc *BandwidthControl) AllowRecv(n int) bool
- func (bc *BandwidthControl) AllowSend(n int) bool
- func (bc *BandwidthControl) Disable()
- func (bc *BandwidthControl) Enable()
- func (bc *BandwidthControl) SetRecvRate(rate int64)
- func (bc *BandwidthControl) SetSendRate(rate int64)
- func (bc *BandwidthControl) Stats() BandwidthStats
- func (bc *BandwidthControl) WaitSend(n int)
- type BandwidthStats
- type BatchConn
- func (bc *BatchConn) Close() error
- func (bc *BatchConn) ReadBatch(msgs []Message, flags int) (int, error)
- func (bc *BatchConn) SetDSCP(dscp int) error
- func (bc *BatchConn) SetReadBuffer(bytes int) error
- func (bc *BatchConn) SetWriteBuffer(bytes int) error
- func (bc *BatchConn) WriteBatch(msgs []Message, flags int) (int, error)
- type BatchReader
- type BatchWriter
- type BlockCrypt
- func NewAESCFB(key []byte) (BlockCrypt, error)
- func NewAESGCM(key []byte) (BlockCrypt, error)
- func NewBlockCrypt(cipherType CipherType, key []byte) (BlockCrypt, error)
- func NewChaCha20Poly1305(key []byte) (BlockCrypt, error)
- func NewNoneCrypt() BlockCrypt
- func NewSalsa20(key []byte) (BlockCrypt, error)
- func NewXChaCha20Poly1305(key []byte) (BlockCrypt, error)
- type Channel
- func (c *Channel) CleanupStaleFragments(currentTime, timeout uint32)
- func (c *Channel) GetRetransmitSegments(currentTime, rto uint32, fastResend uint32) []*Segment
- func (c *Channel) GetSendSegment() *Segment
- func (c *Channel) HasData() bool
- func (c *Channel) ID() uint8
- func (c *Channel) IncrementFastACK(sn uint32)
- func (c *Channel) PendingSend() int
- func (c *Channel) ProcessACK(seq uint32, timestamp uint32) *Segment
- func (c *Channel) ProcessRecv(seg *Segment)
- func (c *Channel) ProcessUNA(una uint32) []*Segment
- func (c *Channel) Recv() []byte
- func (c *Channel) Reset()
- func (c *Channel) Send(data []byte, mode DeliveryMode) uint32
- func (c *Channel) SendWithDefault(data []byte) uint32
- func (c *Channel) SetDefaultMode(mode DeliveryMode)
- func (c *Channel) Stats() ChannelStats
- type ChannelStats
- type CipherType
- type Config
- type ConfigBuilder
- func (b *ConfigBuilder) Build() *Config
- func (b *ConfigBuilder) Channels(n int) *ConfigBuilder
- func (b *ConfigBuilder) DSCP(dscp int) *ConfigBuilder
- func (b *ConfigBuilder) Dial(address string) (*Connection, error)
- func (b *ConfigBuilder) Encrypt(cipher CipherType, key []byte) *ConfigBuilder
- func (b *ConfigBuilder) EncryptWithPassword(cipher CipherType, password string, salt []byte) *ConfigBuilder
- func (b *ConfigBuilder) FEC(dataShards, parityShards int) *ConfigBuilder
- func (b *ConfigBuilder) Fast() *ConfigBuilder
- func (b *ConfigBuilder) FastRecovery() *ConfigBuilder
- func (b *ConfigBuilder) KeepAlive(d time.Duration) *ConfigBuilder
- func (b *ConfigBuilder) Listen(address string) (*Listener, error)
- func (b *ConfigBuilder) MTU(mtu int) *ConfigBuilder
- func (b *ConfigBuilder) NoCongestion() *ConfigBuilder
- func (b *ConfigBuilder) RateLimit(bytesPerSecond int64) *ConfigBuilder
- func (b *ConfigBuilder) Secure(key []byte) *ConfigBuilder
- func (b *ConfigBuilder) SecureWithPassword(password string, salt []byte) *ConfigBuilder
- func (b *ConfigBuilder) SocketBuffers(readSize, writeSize int) *ConfigBuilder
- func (b *ConfigBuilder) Timeout(d time.Duration) *ConfigBuilder
- func (b *ConfigBuilder) Window(send, recv int) *ConfigBuilder
- type CongestionController
- type CongestionStats
- type Conn
- type ConnectOptions
- type Connection
- func Connect(address string) (*Connection, error)
- func ConnectFast(address string) (*Connection, error)
- func ConnectWithTimeout(address string, timeout time.Duration) (*Connection, error)
- func Dial(network, address string) (*Connection, error)
- func DialConfig(network, address string, config *Config) (*Connection, error)
- func DialWithOptions(network, address string, opts *ConnectOptions) (*Connection, error)
- func NewConnection(id uint32, remoteAddr net.Addr, config *Config) *Connection
- func (c *Connection) Close() error
- func (c *Connection) ID() uint32
- func (c *Connection) Input(data []byte) error
- func (c *Connection) IsConnected() bool
- func (c *Connection) LastError() error
- func (c *Connection) LocalAddr() net.Addr
- func (c *Connection) Recv() (uint8, []byte, error)
- func (c *Connection) RecvData() ([]byte, error)
- func (c *Connection) RecvFrom() (channel uint8, data []byte, err error)
- func (c *Connection) RecvTimeout(timeout time.Duration) (uint8, []byte, error)
- func (c *Connection) RemoteAddr() net.Addr
- func (c *Connection) Send(channel uint8, data []byte, mode DeliveryMode) error
- func (c *Connection) SendFast(data []byte) error
- func (c *Connection) SendOn(channel uint8, data []byte) error
- func (c *Connection) SendReliable(data []byte) error
- func (c *Connection) SendStream(data []byte) error
- func (c *Connection) SendUnreliable(data []byte) error
- func (c *Connection) SetDeadline(t time.Time) error
- func (c *Connection) SetOutput(output OutputCallback)
- func (c *Connection) SetReadDeadline(t time.Time) error
- func (c *Connection) SetState(state ConnectionState)
- func (c *Connection) SetWriteDeadline(t time.Time) error
- func (c *Connection) State() ConnectionState
- func (c *Connection) Stats() ConnectionStats
- func (c *Connection) TryRecv() (uint8, []byte, error)
- func (c *Connection) Update()
- type ConnectionState
- type ConnectionStats
- type CounterNonce
- type CryptConfig
- type DeliveryMode
- type Entropy
- type FECConfig
- type FECDecoder
- type FECEncoder
- type FragmentAssembly
- type KCPCongestion
- func (c *KCPCongestion) CanSend(inFlight uint32) bool
- func (c *KCPCongestion) OnACK(acked uint32)
- func (c *KCPCongestion) OnLoss()
- func (c *KCPCongestion) OnTimeout()
- func (c *KCPCongestion) Reset()
- func (c *KCPCongestion) SetNoCongestion(enabled bool)
- func (c *KCPCongestion) SetRemoteWindow(wnd uint32)
- func (c *KCPCongestion) Stats() CongestionStats
- func (c *KCPCongestion) WindowSize() uint32
- type Listener
- type Message
- type NoCongestion
- type NoncePool
- type OutputCallback
- type Packet
- func (p *Packet) Decode(buf []byte) error
- func (p *Packet) Encode(buf []byte) (int, error)
- func (p *Packet) EncodeHeader(buf []byte) error
- func (p *Packet) IsACK() bool
- func (p *Packet) IsConnect() bool
- func (p *Packet) IsFragment() bool
- func (p *Packet) IsOrdered() bool
- func (p *Packet) IsReliable() bool
- func (p *Packet) Reset()
- func (p *Packet) Size() int
- type PoolStats
- type RTTEstimator
- func (r *RTTEstimator) CalculateBackoff(baseRTO int32, transmits uint32) int32
- func (r *RTTEstimator) RTO() int32
- func (r *RTTEstimator) RTTVAR() int32
- func (r *RTTEstimator) SRTT() int32
- func (r *RTTEstimator) SetInterval(interval int32)
- func (r *RTTEstimator) SetMinRTO(minRTO int32)
- func (r *RTTEstimator) SetNoDelay(enabled bool)
- func (r *RTTEstimator) Stats() RTTStats
- func (r *RTTEstimator) Update(rtt int32)
- type RTTStats
- type RateLimiter
- func (r *RateLimiter) Allow(n int) bool
- func (r *RateLimiter) Rate() int64
- func (r *RateLimiter) Reset()
- func (r *RateLimiter) SetBurst(burst int64)
- func (r *RateLimiter) SetRate(rate int64)
- func (r *RateLimiter) Stats() (throttledBytes, throttledCount uint64)
- func (r *RateLimiter) Tokens() int64
- func (r *RateLimiter) Wait(n int)
- func (r *RateLimiter) WaitContext(n int, deadline time.Time) bool
- type RecvBuffer
- type RecvHeap
- type Segment
- type SegmentQueue
- func (q *SegmentQueue) Clear()
- func (q *SegmentQueue) Find(seq uint32) *Segment
- func (q *SegmentQueue) ForEach(fn func(*Segment) bool)
- func (q *SegmentQueue) Len() int
- func (q *SegmentQueue) Peek() *Segment
- func (q *SegmentQueue) Pop() *Segment
- func (q *SegmentQueue) Push(seg *Segment)
- func (q *SegmentQueue) Remove(seq uint32) *Segment
- func (q *SegmentQueue) RemoveUntil(seq uint32) []*Segment
- type SendBuffer
- func (b *SendBuffer) AckUntil(una uint32) []*Segment
- func (b *SendBuffer) Add(seg *Segment)
- func (b *SendBuffer) Clear()
- func (b *SendBuffer) ForEach(fn func(*Segment) bool)
- func (b *SendBuffer) Get(seq uint32) *Segment
- func (b *SendBuffer) GetTimeouts(currentTime uint32) []*Segment
- func (b *SendBuffer) IncrementFastACK(maxACK uint32, threshold uint32) []*Segment
- func (b *SendBuffer) Insert(seg *Segment)
- func (b *SendBuffer) Len() int
- func (b *SendBuffer) Remove(seq uint32) *Segment
- func (b *SendBuffer) RemoveUntil(seq uint32) []*Segment
- type SlidingWindowCounter
- type Stats
- func (s *Stats) AddCurrEstab(delta int64)
- func (s *Stats) AddFECParityShards(n uint64)
- func (s *Stats) AddInBytes(n uint64)
- func (s *Stats) AddOutBytes(n uint64)
- func (s *Stats) AddThrottledBytes(n uint64)
- func (s *Stats) Copy() Stats
- func (s *Stats) GetAvgRTT() uint64
- func (s *Stats) IncrActiveOpens()
- func (s *Stats) IncrAttemptFails()
- func (s *Stats) IncrCryptErrs()
- func (s *Stats) IncrDecryptedPkts()
- func (s *Stats) IncrEarlyRetransSegs()
- func (s *Stats) IncrEncryptedPkts()
- func (s *Stats) IncrEstabResets()
- func (s *Stats) IncrFECRecovered()
- func (s *Stats) IncrFECShardErrs()
- func (s *Stats) IncrFastRetransSegs()
- func (s *Stats) IncrInCsumErrs()
- func (s *Stats) IncrInDupSegs()
- func (s *Stats) IncrInErrs()
- func (s *Stats) IncrInOOOSegs()
- func (s *Stats) IncrInOrderSegs()
- func (s *Stats) IncrInPkts()
- func (s *Stats) IncrInSegs()
- func (s *Stats) IncrLostSegs()
- func (s *Stats) IncrOutPkts()
- func (s *Stats) IncrOutSegs()
- func (s *Stats) IncrPassiveOpens()
- func (s *Stats) IncrRepeatSegs()
- func (s *Stats) IncrRetransSegs()
- func (s *Stats) IncrThrottledPkts()
- func (s *Stats) Reset()
- func (s *Stats) SetCurrEstab(n uint64)
- func (s *Stats) UpdateRTT(rttUs uint64)
- type StatsHistory
- func (h *StatsHistory) GetInBytesPerSecond() float64
- func (h *StatsHistory) GetOutBytesPerSecond() float64
- func (h *StatsHistory) GetPacketsPerSecond() float64
- func (h *StatsHistory) GetRate(getter func(s *Stats) uint64) float64
- func (h *StatsHistory) GetRetransmitRate() float64
- func (h *StatsHistory) Record(s *Stats)
- type StatsSnapshot
Constants ¶
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
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
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
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
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
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)
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
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
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
const BatchSize = 128
BatchSize is the maximum packets per batch I/O operation.
const MaxChannels = 256
MaxChannels is the maximum number of channels per connection
Variables ¶
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
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
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 EncodeACKPayload ¶
EncodeACKPayload encodes ACK information into a payload buffer
func FillRandom ¶
FillRandom fills a buffer using the global entropy source
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 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
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 ¶
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
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) ReadBatch ¶
ReadBatch reads multiple packets in a single syscall. Returns the number of messages read.
func (*BatchConn) SetReadBuffer ¶
SetReadBuffer sets the socket read buffer size
func (*BatchConn) SetWriteBuffer ¶
SetWriteBuffer sets the socket write buffer size
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
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) Pending ¶
func (w *BatchWriter) Pending() int
Pending returns the number of pending messages
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 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 ¶
NewChannel creates a new channel with the given ID
func (*Channel) CleanupStaleFragments ¶
CleanupStaleFragments removes fragment assemblies older than timeout
func (*Channel) GetRetransmitSegments ¶
GetRetransmitSegments returns segments that need retransmission
func (*Channel) GetSendSegment ¶
GetSendSegment retrieves the next segment to send, if any
func (*Channel) IncrementFastACK ¶
IncrementFastACK increments the fast ACK counter for segments before the given sequence
func (*Channel) PendingSend ¶
PendingSend returns the number of segments waiting to be sent
func (*Channel) ProcessACK ¶
ProcessACK handles acknowledgment for a sent segment
func (*Channel) ProcessRecv ¶
ProcessRecv handles an incoming segment for this channel. It manages ordering, deduplication, and fragment reassembly.
func (*Channel) ProcessUNA ¶
ProcessUNA handles cumulative acknowledgment
func (*Channel) Recv ¶
Recv retrieves the next available message from the receive queue. Returns nil if no message is available.
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 ¶
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 (*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) SetChannel ¶
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
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) 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 ¶
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.
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.
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 ¶
Listen creates a new FDP listener on the specified network address. Network should be "udp", "udp4", or "udp6".
func ListenConfig ¶
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.
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 ¶
NewNoncePool creates a nonce pool for the given nonce size
type OutputCallback ¶
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 ¶
Decode deserializes a packet from the provided buffer. Returns an error if the buffer is too small or contains invalid data.
func (*Packet) Encode ¶
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 ¶
EncodeHeader writes only the header portion to the buffer. This is useful when building packets with scatter-gather I/O.
func (*Packet) IsFragment ¶
IsFragment returns true if the packet is a fragment
func (*Packet) IsReliable ¶
IsReliable returns true if the packet requires acknowledgment
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) 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) 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) 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.
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 ¶
IsReliable returns true if this segment requires acknowledgment
func (*Segment) NeedsResend ¶
NeedsResend returns true if the segment needs to be retransmitted
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 (*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) 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) 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 (*Stats) AddCurrEstab ¶
AddCurrEstab adds to current connections
func (*Stats) AddFECParityShards ¶
AddFECParityShards adds FEC parity shards count
func (*Stats) AddThrottledBytes ¶
AddThrottledBytes adds throttled bytes
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) 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) 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) SetCurrEstab ¶
SetCurrEstab sets current connections (use Add/Sub for inc/dec)
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 ¶
StatsSnapshot is a time-series snapshot for rate calculations
Source Files
¶
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) |