Documentation

Datagram Engine

Read time 13 minutes Package: Nalix.Environment
On this page

Namespace: Nalix.Environment.Datagrams (and Nalix.Environment.Options for DatagramEngineOptions)
Assembly: Nalix.Environment

DatagramEngine is the protocol engine of one Nalix Datagram Protocol (NDP v1) session. It does no socket I/O (“sans-IO”): the owner feeds received UDP payloads to Receive, sends whatever Poll produces, and calls OnTimer at NextTimer. Times are microseconds from any monotonic clock, for example DatagramEngine.NowMicros().

The engine implements packet numbers, AEAD protection through IDatagramProtection, ACK ranges, loss detection and NewReno congestion control with pacing, path MTU discovery, keepalive, idle timeout, close and draining, path validation, key update, and the DeliveryMethod modes on independent channels with fragmentation and advertised receive budgets. It is not thread-safe: the owner serializes all calls. The engine owns and disposes the protection.

Source Mapping

  • src/Nalix.Environment/Datagrams/DatagramEngine.cs
  • src/Nalix.Environment/Datagrams/DatagramEngine.Cleanup.cs
  • src/Nalix.Environment/Datagrams/DatagramEngine.Report.cs
  • src/Nalix.Environment/Datagrams/DatagramEngine.Types.cs
  • src/Nalix.Environment/Datagrams/DatagramEngineState.cs
  • src/Nalix.Environment/Datagrams/DatagramCloseCode.cs
  • src/Nalix.Environment/Datagrams/DatagramPeerLimits.cs
  • src/Nalix.Environment/Datagrams/IDatagramEngineHandler.cs
  • src/Nalix.Environment/Options/DatagramEngineOptions.cs

Driving the engine

The owner loop around the engine, showing who calls which member.

Architecture Diagram
flowchart LR
    Socket["UDP socket"] -->|"Receive(datagram, from, now)"| Engine["DatagramEngine"]
    App["Application"] -->|"TrySend / Close"| Engine
    Timer["Timer at NextTimer"] -->|"OnTimer(now)"| Engine
    Engine -->|"Poll(destination, now, out path)"| Socket
    Engine -->|"OnMessage / OnClosed"| Handler["IDatagramEngineHandler"]

After every Receive, TrySend, Close and OnTimer, call Poll repeatedly until it returns 0.

Inside the engine

Send path

How a message becomes a datagram. TrySend copies the message into a priority queue, splitting it into fragments when it exceeds MaxUnfragmentedMessageSize (ReliableSender.cs L80); Poll (DatagramEngine.cs L241) writes retransmissions first, then queued messages by priority, once the congestion window and pacer allow it, and seals the result with the protection.

Architecture Diagram
flowchart LR
    Send["TrySend"] --> Size{"Message size"}
    Size -->|"fits one frame"| Queue["Priority queue"]
    Size -->|"larger, reliable"| Frag["Fragments"]
    Frag --> Queue
    Retx["Retransmit list"] -->|"first"| Write["WriteMessages"]
    Queue --> Gate{"Window and pacer"}
    Gate -->|"open"| Write
    Gate -->|"blocked"| Wait["Wait for OnTimer"]
    Write --> Seal["Seal with AEAD"]
    Seal --> Out["Poll returns datagram"]

Receive path

How a datagram becomes a message. Receive (DatagramEngine.cs L423) drops malformed, duplicate or unauthentic datagrams, then ProcessFrames routes each frame; messages go through ReliableReceiver by delivery method and reach the handler after the whole datagram is processed (DispatchDeliveries).

Architecture Diagram
flowchart LR
    Recv["Receive"] --> Check{"Header, replay, AEAD ok?"}
    Check -->|"no"| Drop["DatagramsDropped"]
    Check -->|"yes"| Frames["ProcessFrames"]
    Frames -->|"ACK"| Loss["Loss recovery"]
    Frames -->|"MESSAGE"| Rx["ReliableReceiver"]
    Rx -->|"fragment"| Asm["Reassembly"]
    Rx -->|"whole message"| Deliver["OnMessage"]
    Asm -->|"complete"| Deliver
    Frames -->|"ack-eliciting"| Ack["AckTracker"]
    Frames -->|"bad frame"| Close["Close with error code"]

Loss recovery and timers

How loss is detected and repaired, driven by ACK frames and by OnTimer (DatagramEngine.Cleanup.cs L182). A packet is lost when three newer packets were acknowledged or its loss time passed (LossRecovery.PacketThreshold); lost messages go back to the retransmit list and the NewReno window shrinks. When no ACK arrives, the probe timeout queues two probes so Poll can send even with a full window. OnTimer also sends keepalive PINGs and ends the session on idle timeout.

Architecture Diagram
flowchart TD
    AckFrame["ACK frame"] --> Rtt["RTT sample"]
    AckFrame --> Acked["Window grows"]
    AckFrame --> Detect["DetectLost"]
    Timer["OnTimer"] --> Due{"Loss time due?"}
    Due -->|"yes"| Detect
    Due -->|"no, PTO due"| Probe["Two probes pending"]
    Detect --> Retx["Retransmit list"]
    Detect --> Cut["Window halves"]
    Retx --> Poll["Poll"]
    Probe --> Poll

DatagramEngine

public sealed partial class DatagramEngine : IDisposable (DatagramEngine.cs L34).

Constructor

public DatagramEngine(
    DatagramEngineOptions options, DatagramPeerLimits peerLimits, IDatagramProtection protection,
    ulong connectionId, bool isServer, IDatagramEngineHandler handler, long now);

(DatagramEngine.cs L108.) options, protection and handler throw ArgumentNullException when null; the constructor then calls options.Validate() (see Validate() rules). Channel count and idle timeout must match the peer’s. peerLimits are the receive budgets the peer advertised in the ticket. The client opens the session with a PING; the server only answers authenticated datagrams (DatagramEngine.cs L134-L135).

Constants

MemberSignatureDescription
MinimumDatagramSizepublic const int MinimumDatagramSizeSmallest valid datagram: 13-byte header, one frame byte, 16-byte tag (DatagramEngine.cs L37).
MaxDatagramSizepublic const int MaxDatagramSize = 1472Largest datagram Poll produces, the largest MTU probe (DatagramEngine.cs L228).
MaxUnfragmentedMessageSizepublic const int MaxUnfragmentedMessageSizeLargest message sent in one MESSAGE frame: DatagramEngineOptions.MinimumMtu minus the datagram header (13), the tag bound (16) and the largest MESSAGE frame header (23), i.e. 1148 bytes (DatagramEngine.Types.cs L20-L21).

Lifecycle and routing

MemberSignatureDescription
Statepublic DatagramEngineState State { get; }Current lifecycle state (L139).
ConnectionIdpublic ulong ConnectionId { get; }The connection identifier given to the constructor (L142).
TryReadConnectionIdpublic static bool TryReadConnectionId(ReadOnlySpan<byte> datagram, out ulong connectionId)Reads the connection id from the cleartext header without authenticating, to route a datagram to its session. Returns false for datagrams shorter than MinimumDatagramSize or with an unknown version or reserved bits set (L151).
NowMicrospublic static long NowMicros()Monotonic time in microseconds, for the now arguments (L166).
Disposepublic void Dispose()Releases every buffer, fails pending ACK receipts and disposes the protection. Raises the close event with NoError if the session had not closed yet (DatagramEngine.Cleanup.cs L23).

Sending

MemberSignatureDescription
TrySendpublic bool TrySend(ReadOnlySpan<byte> message, DeliveryMethod method, byte channel, byte priority, long now)Queues a message (copied). Messages larger than MaxUnfragmentedMessageSize are fragmented and need a reliable ordered or unordered method. Returns false when the session is closing, the message is too large for its method, or the channel’s send queue is full. Higher priority is sent first; levels above 7 are treated as 7. Throws ArgumentOutOfRangeException for an invalid method or a channel at or above ChannelCount (L183, L740-L747).
TrySendWithReceiptpublic Task<bool>? TrySendWithReceipt(ReadOnlySpan<byte> message, DeliveryMethod method, byte channel, byte priority, long now)Queues a reliable message and returns a task that completes with true when every fragment was acknowledged, or false when the session closed first or a newer ReliableSequenced message replaced it. Returns null when not queued. Throws ArgumentException when method is not reliable (L196).
RaiseReceiveLimitspublic void RaiseReceiveLimits(DatagramPeerLimits limits)Raises this side’s advertised receive budgets; a LIMITS frame tells the peer. Budgets never shrink: each value is the maximum of the current and the given one (L213).

Polling, receiving and timers

MemberSignatureDescription
Pollpublic int Poll(Span<byte> destination, long now, out SocketAddress? path)Produces the next datagram, or returns 0 when nothing is due. destination must be at least MaxDatagramSize bytes (ArgumentOutOfRangeException otherwise). path is non-null only for a path challenge sent to an address that is not the active path (L241).
Receivepublic bool Receive(ReadOnlySpan<byte> datagram, SocketAddress? from, long now)Processes one received datagram; true when it authenticated and was processed. from is the sender address on the server (copied when kept) and null on the client. Datagrams that are malformed, too long, for another connection id, duplicate or not authentic increment DatagramsDropped and return false (L423-L433).
OnTimerpublic void OnTimer(long now)Runs the timers that are due: idle timeout, draining, loss detection, probe timeout, keepalive, path validation retries, key discard and fragment expiry (DatagramEngine.Cleanup.cs L182).
NextTimerpublic long NextTimer { get; }Time of the next OnTimer call, or long.MaxValue when none is needed (DatagramEngine.Report.cs L48).
Closepublic void Close(DatagramCloseCode code, string? reason, long now, ulong applicationCode = 0)Queues a CLOSE frame for the next Poll, then drains for three probe timeouts. IdleTimeout throws ArgumentException (local only). At most 256 UTF-8 bytes of reason are sent. applicationCode is used with ApplicationError (DatagramEngine.Cleanup.cs L65).

Diagnostics

All in DatagramEngine.Report.cs.

MemberSignatureDescription
Mtupublic int Mtu { get; }Current path MTU (UDP payload bytes) (L13).
SmoothedRttpublic long SmoothedRtt { get; }Smoothed round-trip time in microseconds (L16).
CongestionWindowpublic long CongestionWindow { get; }Congestion window in bytes (L19).
BytesInFlightpublic long BytesInFlight { get; }Bytes in flight (L22).
DatagramsSentpublic long DatagramsSent { get; private set; }Datagrams sent (L25).
DatagramsReceivedpublic long DatagramsReceived { get; private set; }Authenticated datagrams received (L28).
DatagramsDroppedpublic long DatagramsDropped { get; private set; }Received datagrams dropped (malformed, duplicate, or not authentic) (L31).
DatagramsLostpublic long DatagramsLost { get; private set; }Sent datagrams declared lost (L34).
ActivePathpublic SocketAddress? ActivePath { get; }Validated peer address on the server; null before the first authenticated datagram and on the client (L43).
GenerateReportpublic string GenerateReport()One-line summary (state, mtu, srtt, cwnd, inflight, sent, received, lost, dropped) for diagnostics (L87).

DatagramEngineState

public enum DatagramEngineState : byte (DatagramEngineState.cs L9). Lifecycle of a DatagramEngine.

ValueMeaning
Pending = 0Created; no datagram has authenticated yet.
Established = 1A datagram from the peer authenticated; data flows (set in Receive, DatagramEngine.cs L468).
Draining = 2A CLOSE frame is queued or was sent or received; the session ignores further datagrams.
Closed = 3Closed; nothing is sent or received.

The engine moves one way through four states; the DatagramCloseCode explains why it left Established. Closing by Close, a CLOSE frame, a frame error or the AEAD limit enters Draining first (DatagramEngine.Cleanup.cs L108, L76); only the idle timeout and the end of draining reach Closed (Terminate, L151). Poll then sends the queued CLOSE frame and the drain lasts three probe timeouts.

Architecture Diagram
stateDiagram-v2
    [*] --> Pending : constructor
    Pending --> Established : first datagram authenticates
    Pending --> Draining : Close or error
    Established --> Draining : Close, error, CLOSE frame
    Pending --> Closed : IdleTimeout
    Established --> Closed : IdleTimeout
    Draining --> Closed : drain ends
    Closed --> [*]

DatagramCloseCode

public enum DatagramCloseCode : byte (DatagramCloseCode.cs L9). Why a datagram session closed. Carried in the CLOSE frame, except IdleTimeout, which is local only.

ValueMeaning
NoError = 0Normal close.
InternalError = 1The peer hit an internal error.
ProtocolViolation = 2The peer violated the protocol.
FrameEncodingError = 3A frame could not be decoded, or its type is unknown.
FlowControlError = 4The peer exceeded an advertised receive budget.
IdleTimeout = 5Nothing was received within the idle timeout. Never sent on the wire.
AeadLimitReached = 6Too many datagrams failed to decrypt.
ApplicationError = 7The application closed the session with its own code.

DatagramPeerLimits

public readonly record struct DatagramPeerLimits(long ReceiveBufferBytes, long ChannelReceiveBufferBytes) (DatagramPeerLimits.cs L14). The receive budgets the peer advertised, first in the ticket and later in LIMITS frames. A sender keeps its unreleased reliable bytes within them.

MemberSignatureDescription
ReceiveBufferByteslong (positional)Total bytes the peer buffers for ordering and reassembly.
ChannelReceiveBufferByteslong (positional)Bytes the peer buffers per channel.
Defaultpublic static DatagramPeerLimits Default { get; }Limits of a peer that uses a default DatagramEngineOptions (L19).
Frompublic static DatagramPeerLimits From(DatagramEngineOptions options)Limits a side with options advertises; throws ArgumentNullException for null (L24-L28).

IDatagramEngineHandler

public interface IDatagramEngineHandler (IDatagramEngineHandler.cs L13). Receives the output of a DatagramEngine. It is called synchronously from the engine call that produced the event, under the owner’s lock, so implementations hand work off instead of blocking.

MemberSignatureDescription
OnMessagevoid OnMessage(BufferLease message, DeliveryMethod method, byte channel)A complete message was delivered. Ownership of message passes to the handler, which disposes it (L21).
OnClosedvoid OnClosed(DatagramCloseCode code, ulong applicationCode, string reason, bool remote)The session closed, by either side or by idle timeout. Raised once. applicationCode is meaningful when code is ApplicationError; reason may be empty; remote is true when the peer closed the session (L30).

BufferLease is from Nalix.Environment.Memory; DeliveryMethod is from Nalix.Abstractions.Networking.Datagrams.

DatagramEngineOptions

public sealed partial class DatagramEngineOptions : ConfigurationLoader, IValidatableConfiguration (namespace Nalix.Environment.Options, DatagramEngineOptions.cs L16). Settings of one side of a datagram session. The server advertises channel count, idle timeout, message size and receive budgets in the ticket, and the client uses the same values. It is an .ini-bound options class (see Configuration); the section name is [DatagramEngine].

Constants

MemberValueDescription
MinimumMtu1200Smallest MTU, safe on IPv4 and IPv6 paths; every frame is sized to fit in it (L19).
MaxChannels64Largest number of channels (L22).

Properties

PropertyTypeDefaultRangeDescription
ChannelCountint81..64Number of channels in use (L27).
IdleTimeoutMsint15_000100..3,600,000Idle timeout in milliseconds (L32).
MaxAckDelayMsint251..1,000Longest an acknowledgement is delayed, in milliseconds (L37).
UnreliableExpiryMsint1001..60,000How long a queued unreliable message may wait before it is dropped (L42).
MaxMessageSizeint1048576 (1 MiB)1..67,108,864 (64 MiB)Largest message accepted by a send or reassembled from fragments (L47).
ReceiveBufferByteslong4194304 (4 MiB)1..long.MaxValueTotal bytes this side buffers for ordering and reassembly; advertised to the peer (L52).
ChannelReceiveBufferByteslong2097152 (2 MiB)1..long.MaxValueBytes this side buffers per channel; advertised to the peer (L57).
SendQueueBytesPerChannellong4194304 (4 MiB)1..long.MaxValueBytes that may wait in the send queue of one channel (L62).
MaxOpenFragmentStreamsint641..65,535Largest number of fragmented messages reassembled at once (L67).
FragmentTimeoutMsint10_000100..3,600,000How long an incomplete fragmented message is kept (L72).
EnableMtuProbingbooltruen/aProbe the path MTU above MinimumMtu (L76).
KeyUpdatePacketIntervallong8388608 (2^23)16..2^40Packets sent with one key before a key update (L81).
KeyUpdateIntervalMslong3_600_000 (1 hour)1,000..604,800,000 (7 days)Time one key is used before a key update (L86).

Validate() rules

public void Validate() (L92) throws ValidationException (Nalix.Abstractions.Exceptions) when:

  1. Any property is outside its [ValueRange] above (ValidateDataAnnotations(), L94).
  2. ChannelReceiveBufferBytes < MaxMessageSize + 65536: a fragmented message is released by the peer only once complete, so one must fit in a channel budget with its fragment headers and per-message overhead (L98-L103).
  3. ReceiveBufferBytes < ChannelReceiveBufferBytes (L105-L109).
  4. SendQueueBytesPerChannel < MaxMessageSize (L111-L115).

The defaults satisfy all three cross-checks. If you raise MaxMessageSize, raise ChannelReceiveBufferBytes, ReceiveBufferBytes and SendQueueBytesPerChannel with it. DatagramEngine’s constructor calls Validate() for you.

Usage example

A minimal server-side owner loop. The protection, handler and socket plumbing are application code; connectionId and protection come from your ticket and key exchange.

using System.Net;
using Nalix.Abstractions.Networking.Datagrams;
using Nalix.Environment.Datagrams;
using Nalix.Environment.Memory;
using Nalix.Environment.Options;

sealed class SessionHandler : IDatagramEngineHandler
{
    public void OnMessage(BufferLease message, DeliveryMethod method, byte channel)
    {
        // Hand off quickly; the handler owns the lease.
        using (message)
        {
            // process the Nalix frame on a worker
        }
    }

    public void OnClosed(DatagramCloseCode code, ulong applicationCode, string reason, bool remote)
        => Console.WriteLine($"closed: {code} remote={remote} reason={reason}");
}

DatagramEngineOptions options = new() { ChannelCount = 4, IdleTimeoutMs = 10_000 };
DatagramPeerLimits peer = DatagramPeerLimits.Default;

using DatagramEngine engine = new(
    options, peer, protection, connectionId, isServer: true, new SessionHandler(), DatagramEngine.NowMicros());

// Inbound datagram from the socket:
engine.Receive(datagram, remoteEndPoint.Serialize(), DatagramEngine.NowMicros());

// Application send on channel 0, reliable and ordered:
engine.TrySend(payload, DeliveryMethod.ReliableOrdered, channel: 0, priority: 0, DatagramEngine.NowMicros());

// Drain output:
Span<byte> buffer = stackalloc byte[DatagramEngine.MaxDatagramSize];
int length;
while ((length = engine.Poll(buffer, DatagramEngine.NowMicros(), out SocketAddress? path)) > 0)
{
    // send buffer[..length] to `path` when non-null, otherwise to the active peer
}

// When the timer set for engine.NextTimer fires:
engine.OnTimer(DatagramEngine.NowMicros());

// Graceful shutdown (then keep calling Poll so the CLOSE frame is sent):
engine.Close(DatagramCloseCode.NoError, "bye", DatagramEngine.NowMicros());