Port RUDP reliability core to C#
This commit is contained in:
parent
105f564e76
commit
62cd1db32b
3 changed files with 545 additions and 6 deletions
|
|
@ -1,5 +1,7 @@
|
|||
using System;
|
||||
using System.Buffers.Binary;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
|
|
@ -408,6 +410,417 @@ namespace GameCult.Networking
|
|||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Payload delivered by the CultNet RUDP reliability state machine.
|
||||
/// </summary>
|
||||
public sealed class CultNetRudpDeliveredFrame
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the logical channel id.
|
||||
/// </summary>
|
||||
public string ChannelId { get; set; } = string.Empty;
|
||||
/// <summary>
|
||||
/// Gets or sets the delivered payload bytes.
|
||||
/// </summary>
|
||||
public byte[] Payload { get; set; } = Array.Empty<byte>();
|
||||
/// <summary>
|
||||
/// Gets or sets the packet sequence that delivered the frame.
|
||||
/// </summary>
|
||||
public uint Sequence { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Result of feeding one packet into a CultNet RUDP session.
|
||||
/// </summary>
|
||||
public sealed class CultNetRudpReceiveResult
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets delivered frames.
|
||||
/// </summary>
|
||||
public IReadOnlyList<CultNetRudpDeliveredFrame> Delivered { get; set; } = Array.Empty<CultNetRudpDeliveredFrame>();
|
||||
/// <summary>
|
||||
/// Gets or sets an optional immediate reply packet.
|
||||
/// </summary>
|
||||
public CultNetRudpPacket? Reply { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Options for the in-memory CultNet RUDP reliability state machine.
|
||||
/// </summary>
|
||||
public sealed class CultNetRudpSessionOptions
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the connection/session binding id.
|
||||
/// </summary>
|
||||
public uint ConnectionId { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets the first local packet sequence.
|
||||
/// </summary>
|
||||
public uint InitialSequence { get; set; } = 1;
|
||||
/// <summary>
|
||||
/// Gets or sets the resend delay in milliseconds.
|
||||
/// </summary>
|
||||
public long ResendDelayMs { get; set; } = 250;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Send options for RUDP data packets.
|
||||
/// </summary>
|
||||
public sealed class CultNetRudpSendOptions
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets whether the packet participates in reliable delivery.
|
||||
/// </summary>
|
||||
public bool Reliable { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets whether the packet participates in ordered delivery.
|
||||
/// </summary>
|
||||
public bool Ordered { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets whether the packet is latest-state sequenced.
|
||||
/// </summary>
|
||||
public bool Sequenced { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets the current logical time in milliseconds.
|
||||
/// </summary>
|
||||
public long NowMs { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Socket-free reliability state machine for CultNet RUDP.
|
||||
/// </summary>
|
||||
public sealed class CultNetRudpSession
|
||||
{
|
||||
private sealed class PendingReliablePacket
|
||||
{
|
||||
public CultNetRudpPacket Packet { get; set; } = new CultNetRudpPacket();
|
||||
public long LastSentAtMs { get; set; }
|
||||
}
|
||||
|
||||
private uint _nextSequence;
|
||||
private bool _connected;
|
||||
private uint? _highestReceivedSequence;
|
||||
private readonly HashSet<uint> _receivedSequences = new HashSet<uint>();
|
||||
private readonly Dictionary<uint, PendingReliablePacket> _pendingReliable = new Dictionary<uint, PendingReliablePacket>();
|
||||
private readonly Dictionary<string, uint> _orderedNextSequenceByChannel = new Dictionary<string, uint>(StringComparer.Ordinal);
|
||||
private readonly Dictionary<string, SortedDictionary<uint, CultNetRudpDeliveredFrame>> _orderedBuffers =
|
||||
new Dictionary<string, SortedDictionary<uint, CultNetRudpDeliveredFrame>>(StringComparer.Ordinal);
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a RUDP reliability session.
|
||||
/// </summary>
|
||||
public CultNetRudpSession(CultNetRudpSessionOptions options)
|
||||
{
|
||||
if (options == null) throw new ArgumentNullException(nameof(options));
|
||||
ConnectionId = options.ConnectionId;
|
||||
_nextSequence = options.InitialSequence;
|
||||
ResendDelayMs = options.ResendDelayMs;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the connection/session binding id.
|
||||
/// </summary>
|
||||
public uint ConnectionId { get; }
|
||||
/// <summary>
|
||||
/// Gets the resend delay in milliseconds.
|
||||
/// </summary>
|
||||
public long ResendDelayMs { get; }
|
||||
/// <summary>
|
||||
/// Gets whether the session has completed the connect/accept handshake.
|
||||
/// </summary>
|
||||
public bool Connected => _connected;
|
||||
/// <summary>
|
||||
/// Gets reliable packet sequences awaiting acknowledgement.
|
||||
/// </summary>
|
||||
public IReadOnlyList<uint> PendingReliableSequences => _pendingReliable.Keys.OrderBy(value => value).ToArray();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a reliable ordered connect packet.
|
||||
/// </summary>
|
||||
public CultNetRudpPacket CreateConnect(long nowMs = 0, byte[]? payload = null)
|
||||
{
|
||||
var packet = CreatePacket(CultNetRudpPacketType.Connect, "control", payload ?? Array.Empty<byte>(), reliable: true, ordered: true, sequenced: false);
|
||||
TrackReliable(packet, nowMs);
|
||||
return packet;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Accepts a connect packet and returns a reliable ordered accept packet.
|
||||
/// </summary>
|
||||
public CultNetRudpPacket AcceptConnect(CultNetRudpPacket packet, long nowMs = 0, byte[]? payload = null)
|
||||
{
|
||||
RequireConnection(packet);
|
||||
if (packet.PacketType != CultNetRudpPacketType.Connect)
|
||||
{
|
||||
throw new InvalidOperationException($"Expected RUDP connect packet, got {packet.PacketType}.");
|
||||
}
|
||||
|
||||
RememberReceived(packet.Sequence);
|
||||
_connected = true;
|
||||
var response = CreatePacket(CultNetRudpPacketType.Accept, "control", payload ?? Array.Empty<byte>(), reliable: true, ordered: true, sequenced: false);
|
||||
TrackReliable(response, nowMs);
|
||||
return response;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a data packet.
|
||||
/// </summary>
|
||||
public CultNetRudpPacket Send(string channelId, byte[] payload, CultNetRudpSendOptions? options = null)
|
||||
{
|
||||
if (!_connected)
|
||||
{
|
||||
throw new InvalidOperationException("Cannot send RUDP data before the session is connected.");
|
||||
}
|
||||
|
||||
options ??= new CultNetRudpSendOptions();
|
||||
var packet = CreatePacket(
|
||||
CultNetRudpPacketType.Data,
|
||||
channelId,
|
||||
payload,
|
||||
options.Reliable,
|
||||
options.Ordered,
|
||||
options.Sequenced);
|
||||
if (packet.Reliable)
|
||||
{
|
||||
TrackReliable(packet, options.NowMs);
|
||||
}
|
||||
return packet;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Applies a remote packet to the session.
|
||||
/// </summary>
|
||||
public CultNetRudpReceiveResult Receive(CultNetRudpPacket packet, long nowMs = 0)
|
||||
{
|
||||
RequireConnection(packet);
|
||||
ApplyAcknowledgements(packet);
|
||||
|
||||
if (packet.PacketType == CultNetRudpPacketType.Accept)
|
||||
{
|
||||
RememberReceived(packet.Sequence);
|
||||
_connected = true;
|
||||
return new CultNetRudpReceiveResult();
|
||||
}
|
||||
|
||||
if (packet.PacketType == CultNetRudpPacketType.Ping)
|
||||
{
|
||||
RememberReceived(packet.Sequence);
|
||||
return new CultNetRudpReceiveResult
|
||||
{
|
||||
Reply = CreatePacket(
|
||||
CultNetRudpPacketType.Pong,
|
||||
"control",
|
||||
packet.Payload ?? Array.Empty<byte>(),
|
||||
reliable: false,
|
||||
ordered: false,
|
||||
sequenced: false)
|
||||
};
|
||||
}
|
||||
|
||||
if (packet.PacketType == CultNetRudpPacketType.Ack || packet.PacketType == CultNetRudpPacketType.Pong)
|
||||
{
|
||||
RememberReceived(packet.Sequence);
|
||||
return new CultNetRudpReceiveResult();
|
||||
}
|
||||
|
||||
if (packet.PacketType != CultNetRudpPacketType.Data)
|
||||
{
|
||||
return new CultNetRudpReceiveResult();
|
||||
}
|
||||
|
||||
var duplicate = _receivedSequences.Contains(packet.Sequence);
|
||||
RememberReceived(packet.Sequence);
|
||||
if (duplicate)
|
||||
{
|
||||
return new CultNetRudpReceiveResult();
|
||||
}
|
||||
|
||||
var frame = new CultNetRudpDeliveredFrame
|
||||
{
|
||||
ChannelId = packet.ChannelId,
|
||||
Payload = packet.Payload ?? Array.Empty<byte>(),
|
||||
Sequence = packet.Sequence
|
||||
};
|
||||
|
||||
return new CultNetRudpReceiveResult
|
||||
{
|
||||
Delivered = packet.Ordered ? DeliverOrdered(frame) : new[] { frame }
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a packet carrying the current acknowledgement state.
|
||||
/// </summary>
|
||||
public CultNetRudpPacket CreateAck()
|
||||
{
|
||||
return CreatePacket(CultNetRudpPacketType.Ack, "control", Array.Empty<byte>(), reliable: false, ordered: false, sequenced: false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns reliable packets due for resend at the supplied logical time.
|
||||
/// </summary>
|
||||
public IReadOnlyList<CultNetRudpPacket> DueResends(long nowMs)
|
||||
{
|
||||
var due = new List<CultNetRudpPacket>();
|
||||
foreach (var pending in _pendingReliable.Values)
|
||||
{
|
||||
if (nowMs - pending.LastSentAtMs >= ResendDelayMs)
|
||||
{
|
||||
pending.LastSentAtMs = nowMs;
|
||||
due.Add(ClonePacket(pending.Packet));
|
||||
}
|
||||
}
|
||||
|
||||
return due.OrderBy(packet => packet.Sequence).ToArray();
|
||||
}
|
||||
|
||||
private CultNetRudpPacket CreatePacket(
|
||||
CultNetRudpPacketType packetType,
|
||||
string channelId,
|
||||
byte[] payload,
|
||||
bool reliable,
|
||||
bool ordered,
|
||||
bool sequenced)
|
||||
{
|
||||
var sequence = _nextSequence;
|
||||
_nextSequence = checked(_nextSequence + 1);
|
||||
var (ack, ackMask) = AckState();
|
||||
return new CultNetRudpPacket
|
||||
{
|
||||
PacketType = packetType,
|
||||
ConnectionId = ConnectionId,
|
||||
Sequence = sequence,
|
||||
Ack = ack,
|
||||
AckMask = ackMask,
|
||||
ChannelId = channelId,
|
||||
Reliable = reliable,
|
||||
Ordered = ordered,
|
||||
Sequenced = sequenced,
|
||||
Payload = payload ?? Array.Empty<byte>()
|
||||
};
|
||||
}
|
||||
|
||||
private void TrackReliable(CultNetRudpPacket packet, long nowMs)
|
||||
{
|
||||
_pendingReliable[packet.Sequence] = new PendingReliablePacket
|
||||
{
|
||||
Packet = ClonePacket(packet),
|
||||
LastSentAtMs = nowMs
|
||||
};
|
||||
}
|
||||
|
||||
private void ApplyAcknowledgements(CultNetRudpPacket packet)
|
||||
{
|
||||
_pendingReliable.Remove(packet.Ack);
|
||||
for (var bit = 0; bit < 32; bit++)
|
||||
{
|
||||
if ((packet.AckMask & (1u << bit)) != 0 && packet.Ack > bit)
|
||||
{
|
||||
_pendingReliable.Remove(packet.Ack - (uint)bit - 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void RememberReceived(uint sequence)
|
||||
{
|
||||
_receivedSequences.Add(sequence);
|
||||
if (!_highestReceivedSequence.HasValue || sequence > _highestReceivedSequence.Value)
|
||||
{
|
||||
_highestReceivedSequence = sequence;
|
||||
}
|
||||
}
|
||||
|
||||
private (uint Ack, uint AckMask) AckState()
|
||||
{
|
||||
var ack = _highestReceivedSequence ?? 0;
|
||||
uint ackMask = 0;
|
||||
for (var bit = 0; bit < 32; bit++)
|
||||
{
|
||||
if (ack > bit && _receivedSequences.Contains(ack - (uint)bit - 1))
|
||||
{
|
||||
ackMask |= 1u << bit;
|
||||
}
|
||||
}
|
||||
|
||||
return (ack, ackMask);
|
||||
}
|
||||
|
||||
private IReadOnlyList<CultNetRudpDeliveredFrame> DeliverOrdered(CultNetRudpDeliveredFrame frame)
|
||||
{
|
||||
if (!_orderedNextSequenceByChannel.TryGetValue(frame.ChannelId, out var next))
|
||||
{
|
||||
_orderedNextSequenceByChannel[frame.ChannelId] = frame.Sequence + 1;
|
||||
return new[] { frame }.Concat(DrainOrdered(frame.ChannelId)).ToArray();
|
||||
}
|
||||
|
||||
if (frame.Sequence < next)
|
||||
{
|
||||
return Array.Empty<CultNetRudpDeliveredFrame>();
|
||||
}
|
||||
|
||||
if (frame.Sequence > next)
|
||||
{
|
||||
if (!_orderedBuffers.TryGetValue(frame.ChannelId, out var buffer))
|
||||
{
|
||||
buffer = new SortedDictionary<uint, CultNetRudpDeliveredFrame>();
|
||||
_orderedBuffers[frame.ChannelId] = buffer;
|
||||
}
|
||||
|
||||
buffer[frame.Sequence] = frame;
|
||||
return Array.Empty<CultNetRudpDeliveredFrame>();
|
||||
}
|
||||
|
||||
_orderedNextSequenceByChannel[frame.ChannelId] = next + 1;
|
||||
return new[] { frame }.Concat(DrainOrdered(frame.ChannelId)).ToArray();
|
||||
}
|
||||
|
||||
private IReadOnlyList<CultNetRudpDeliveredFrame> DrainOrdered(string channelId)
|
||||
{
|
||||
var delivered = new List<CultNetRudpDeliveredFrame>();
|
||||
if (!_orderedBuffers.TryGetValue(channelId, out var buffer))
|
||||
{
|
||||
return delivered;
|
||||
}
|
||||
|
||||
while (_orderedNextSequenceByChannel.TryGetValue(channelId, out var next) && buffer.TryGetValue(next, out var frame))
|
||||
{
|
||||
buffer.Remove(next);
|
||||
delivered.Add(frame);
|
||||
_orderedNextSequenceByChannel[channelId] = next + 1;
|
||||
}
|
||||
|
||||
return delivered;
|
||||
}
|
||||
|
||||
private void RequireConnection(CultNetRudpPacket packet)
|
||||
{
|
||||
if (packet.ConnectionId != ConnectionId)
|
||||
{
|
||||
throw new InvalidOperationException($"RUDP packet connection id {packet.ConnectionId} does not match {ConnectionId}.");
|
||||
}
|
||||
}
|
||||
|
||||
private static CultNetRudpPacket ClonePacket(CultNetRudpPacket packet)
|
||||
{
|
||||
return new CultNetRudpPacket
|
||||
{
|
||||
PacketType = packet.PacketType,
|
||||
ConnectionId = packet.ConnectionId,
|
||||
Sequence = packet.Sequence,
|
||||
Ack = packet.Ack,
|
||||
AckMask = packet.AckMask,
|
||||
ChannelId = packet.ChannelId,
|
||||
Reliable = packet.Reliable,
|
||||
Ordered = packet.Ordered,
|
||||
Sequenced = packet.Sequenced,
|
||||
FragmentId = packet.FragmentId,
|
||||
FragmentIndex = packet.FragmentIndex,
|
||||
FragmentCount = packet.FragmentCount,
|
||||
Payload = packet.Payload?.ToArray() ?? Array.Empty<byte>()
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Transport connection for the current TCP length-prefixed CultNet schema lane.
|
||||
/// </summary>
|
||||
|
|
|
|||
Loading…
Reference in a new issue