Route LiteNetLib service sends through adapter
This commit is contained in:
parent
e2ea266136
commit
bcdcc8035f
5 changed files with 111 additions and 31 deletions
|
|
@ -151,10 +151,10 @@ Current progress:
|
|||
both the modern reliable ordered `schema` channel and the legacy reliable
|
||||
ordered `legacy` union-message channel, so LiteNetLib is described as an
|
||||
adapter instead of remaining the hidden default. `NetPeer` send helpers now
|
||||
route through `LiteNetLibTransportConnection`, so outbound schema and legacy
|
||||
messages share one channel-aware ReliableOrdered adapter surface, and
|
||||
`Client`/`Server` receive callbacks classify inbound payloads through the
|
||||
same adapter before dispatching schema-v0 or legacy messages.
|
||||
route through `LiteNetLibTransportConnection`; `Client` and `Server` now keep
|
||||
a per-peer adapter and route their own schema/legacy sends through it as
|
||||
well. Inbound payload classification and transfer stats also belong to that
|
||||
channel-aware adapter before dispatching schema-v0 or legacy messages.
|
||||
- TypeScript has the first narrow transport connection port:
|
||||
`TcpFramedTransportConnection` owns length-prefixed frame delivery, exposes
|
||||
frame/close/error events, `send(channel, payload)`, `close`, and transfer
|
||||
|
|
|
|||
|
|
@ -44,6 +44,7 @@ namespace GameCult.Networking
|
|||
public event Action<ClientReconnectState>? OnReconnectStateChanged;
|
||||
private NetManager? _client;
|
||||
private NetPeer? _peer;
|
||||
private LiteNetLibTransportConnection? _transportConnection;
|
||||
private IDisposable? _pollSubscription;
|
||||
private IDisposable? _reconnectSubscription;
|
||||
private bool _disposed;
|
||||
|
|
@ -163,7 +164,7 @@ namespace GameCult.Networking
|
|||
{
|
||||
Logger.LogDebug($"Sending message {typeof(T).Name}");
|
||||
}
|
||||
_peer.Send(m);
|
||||
(_transportConnection ??= new LiteNetLibTransportConnection(_peer)).SendLegacy(m);
|
||||
}
|
||||
else Logger.LogError("Cannot send, client is not verified!");
|
||||
}
|
||||
|
|
@ -187,7 +188,7 @@ namespace GameCult.Networking
|
|||
if (AllowUnverifiedCultNetMessages || Verified || message is CultNetLoginMessage or CultNetRegisterMessage or CultNetVerifyMessage)
|
||||
{
|
||||
Logger.LogDebug($"Sending CultNet schema message {message.SchemaVersion}");
|
||||
_peer.SendCultNet(message);
|
||||
(_transportConnection ??= new LiteNetLibTransportConnection(_peer)).SendSchema(message);
|
||||
}
|
||||
else
|
||||
{
|
||||
|
|
@ -400,7 +401,8 @@ namespace GameCult.Networking
|
|||
try
|
||||
{
|
||||
var bytes = reader.GetRemainingBytes();
|
||||
var frame = LiteNetLibTransportConnection.Decode(bytes);
|
||||
var transport = _transportConnection ??= new LiteNetLibTransportConnection(peer);
|
||||
var frame = transport.Receive(bytes);
|
||||
if (string.Equals(frame.ChannelId, "schema", StringComparison.Ordinal))
|
||||
{
|
||||
var cultNetMessage = LiteNetLibTransportConnection.DecodeSchema(frame);
|
||||
|
|
@ -457,12 +459,13 @@ namespace GameCult.Networking
|
|||
{
|
||||
Logger.LogInfo($"Peer {peer.Address}:{peer.Port} connected.");
|
||||
_peer = peer;
|
||||
_transportConnection = new LiteNetLibTransportConnection(peer);
|
||||
_reconnectController.Reset();
|
||||
SetReconnectState(ClientReconnectState.Idle);
|
||||
if (Verified)
|
||||
{
|
||||
var nonce = Secret.NewNonce;
|
||||
peer.Send(new VerifyMessage
|
||||
_transportConnection.SendLegacy(new VerifyMessage
|
||||
{
|
||||
Nonce = nonce,
|
||||
Session = Secret.EncryptString(_sessionToken, nonce, _security) ?? Array.Empty<byte>()
|
||||
|
|
@ -576,6 +579,7 @@ namespace GameCult.Networking
|
|||
{
|
||||
_pollSubscription?.Dispose();
|
||||
_pollSubscription = null;
|
||||
_transportConnection = null;
|
||||
|
||||
if (_peer != null)
|
||||
{
|
||||
|
|
|
|||
|
|
@ -2055,7 +2055,7 @@ namespace GameCult.Networking
|
|||
/// </summary>
|
||||
public sealed class LiteNetLibTransportConnection
|
||||
{
|
||||
private readonly NetPeer _peer;
|
||||
private readonly NetPeer? _peer;
|
||||
private readonly CultNetTransportStats _stats = new CultNetTransportStats();
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -2067,6 +2067,14 @@ namespace GameCult.Networking
|
|||
Profile = profile ?? CultNetTransportProfiles.CreateLiteNetLib("csharp-litenetlib-peer");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a receive-only channel-aware adapter for LiteNetLib payload classification.
|
||||
/// </summary>
|
||||
public LiteNetLibTransportConnection(CultNetTransportProfile? profile = null)
|
||||
{
|
||||
Profile = profile ?? CultNetTransportProfiles.CreateLiteNetLib("csharp-litenetlib-peer");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the transport profile this adapter implements.
|
||||
/// </summary>
|
||||
|
|
@ -2077,12 +2085,24 @@ namespace GameCult.Networking
|
|||
/// </summary>
|
||||
public CultNetTransportStats Stats => _stats.Snapshot();
|
||||
|
||||
/// <summary>
|
||||
/// Classifies an inbound LiteNetLib payload into the adapter's schema or legacy channel shape.
|
||||
/// </summary>
|
||||
public CultNetTransportFrame Receive(byte[] payload)
|
||||
{
|
||||
var frame = Decode(payload);
|
||||
_stats.BytesReceived += frame.Payload.Length;
|
||||
_stats.FramesReceived++;
|
||||
return frame;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sends a payload over a supported LiteNetLib transport channel.
|
||||
/// </summary>
|
||||
public void Send(string channelId, byte[] payload)
|
||||
{
|
||||
if (payload == null) throw new ArgumentNullException(nameof(payload));
|
||||
if (_peer == null) throw new InvalidOperationException("A LiteNetLib peer is required to send through this transport.");
|
||||
if (!string.Equals(channelId, "schema", StringComparison.Ordinal)
|
||||
&& !string.Equals(channelId, "legacy", StringComparison.Ordinal))
|
||||
{
|
||||
|
|
|
|||
|
|
@ -264,7 +264,7 @@ namespace GameCult.Networking
|
|||
listener.PeerConnectedEvent += peer =>
|
||||
{
|
||||
Logger.LogInfo($"User Connected: {peer.Address}");
|
||||
_users.TryAdd(peer.Id, new User { Peer = peer });
|
||||
_users.TryAdd(peer.Id, new User { Peer = peer, Transport = new LiteNetLibTransportConnection(peer) });
|
||||
};
|
||||
|
||||
listener.PeerDisconnectedEvent += (peer, info) =>
|
||||
|
|
@ -286,8 +286,10 @@ namespace GameCult.Networking
|
|||
try
|
||||
{
|
||||
var bytes = reader.GetRemainingBytes();
|
||||
var user = _users.GetOrAdd(peer.Id, _ => new User { Peer = peer });
|
||||
var frame = LiteNetLibTransportConnection.Decode(bytes);
|
||||
var user = _users.GetOrAdd(peer.Id, _ => new User { Peer = peer, Transport = new LiteNetLibTransportConnection(peer) });
|
||||
user.Transport ??= new LiteNetLibTransportConnection(peer);
|
||||
var transport = user.Transport;
|
||||
var frame = transport.Receive(bytes);
|
||||
if (string.Equals(frame.ChannelId, "schema", StringComparison.Ordinal))
|
||||
{
|
||||
var cultNetMessage = LiteNetLibTransportConnection.DecodeSchema(frame);
|
||||
|
|
@ -321,7 +323,7 @@ namespace GameCult.Networking
|
|||
|
||||
if (message is LoginMessage or RegisterMessage && !CheckAuthRateLimit(peer.Address.ToString()))
|
||||
{
|
||||
peer.Send(new ErrorMessage { Error = "Too Many Attempts" });
|
||||
SendLegacy(peer, new ErrorMessage { Error = "Too Many Attempts" });
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
@ -354,7 +356,7 @@ namespace GameCult.Networking
|
|||
}
|
||||
else
|
||||
{
|
||||
peer.Send(new ErrorMessage { Error = "User Not Verified" });
|
||||
SendLegacy(peer, new ErrorMessage { Error = "User Not Verified" });
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
|
|
@ -367,13 +369,13 @@ namespace GameCult.Networking
|
|||
{
|
||||
if (!IsValidUsername(message.Name))
|
||||
{
|
||||
message.Peer?.Send(new ErrorMessage { Error = "Username Invalid" });
|
||||
SendLegacy(message.Peer, new ErrorMessage { Error = "Username Invalid" });
|
||||
return;
|
||||
}
|
||||
|
||||
if (_database.GetByName<PlayerData>(message.Name) != null)
|
||||
{
|
||||
message.Peer?.Send(new ErrorMessage { Error = "Username Taken" });
|
||||
SendLegacy(message.Peer, new ErrorMessage { Error = "Username Taken" });
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
@ -382,7 +384,7 @@ namespace GameCult.Networking
|
|||
var data = SessionData(user);
|
||||
if (data == null)
|
||||
{
|
||||
message.Peer.Send(new ErrorMessage { Error = "User Not Verified" });
|
||||
SendLegacy(message.Peer, new ErrorMessage { Error = "User Not Verified" });
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
@ -398,7 +400,7 @@ namespace GameCult.Networking
|
|||
{
|
||||
if (!IsVerified(user) && !CanProcessBeforeVerification(message))
|
||||
{
|
||||
peer.SendCultNet(new CultNetErrorMessage { Error = "User Not Verified" });
|
||||
SendSchema(peer, new CultNetErrorMessage { Error = "User Not Verified" });
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
@ -454,31 +456,31 @@ namespace GameCult.Networking
|
|||
|
||||
if (string.IsNullOrWhiteSpace(name) || !IsValidUsername(name))
|
||||
{
|
||||
peer.Send(new ErrorMessage { Error = "Username Invalid" });
|
||||
SendLegacy(peer, new ErrorMessage { Error = "Username Invalid" });
|
||||
return;
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(email) || !IsValidEmail(email))
|
||||
{
|
||||
peer.Send(new ErrorMessage { Error = "Email Invalid" });
|
||||
SendLegacy(peer, new ErrorMessage { Error = "Email Invalid" });
|
||||
return;
|
||||
}
|
||||
|
||||
if (_database.GetByIndex<PlayerData>("Email", email) != null)
|
||||
{
|
||||
peer.Send(new ErrorMessage { Error = "Email Taken" });
|
||||
SendLegacy(peer, new ErrorMessage { Error = "Email Taken" });
|
||||
return;
|
||||
}
|
||||
|
||||
if (_database.GetByName<PlayerData>(name) != null)
|
||||
{
|
||||
peer.Send(new ErrorMessage { Error = "Username Taken" });
|
||||
SendLegacy(peer, new ErrorMessage { Error = "Username Taken" });
|
||||
return;
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(password))
|
||||
{
|
||||
peer.Send(new ErrorMessage { Error = "Password Invalid" });
|
||||
SendLegacy(peer, new ErrorMessage { Error = "Password Invalid" });
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
@ -500,20 +502,20 @@ namespace GameCult.Networking
|
|||
var token = Secret.DecryptString(verify.Session, verify.Nonce, _security);
|
||||
if (!Secret.TryValidateSessionToken(token, _security, out var playerId, out _, out var sessionVersion))
|
||||
{
|
||||
peer.Send(new ErrorMessage { Error = "Session Invalid" });
|
||||
SendLegacy(peer, new ErrorMessage { Error = "Session Invalid" });
|
||||
return;
|
||||
}
|
||||
|
||||
var player = _database.GetByIndex<PlayerData>("PlayerId", playerId.ToString("D"));
|
||||
if (player == null)
|
||||
{
|
||||
peer.Send(new ErrorMessage { Error = "Session Not Found" });
|
||||
SendLegacy(peer, new ErrorMessage { Error = "Session Not Found" });
|
||||
return;
|
||||
}
|
||||
|
||||
if (player.SessionVersion != sessionVersion)
|
||||
{
|
||||
peer.Send(new ErrorMessage { Error = "Session Superseded" });
|
||||
SendLegacy(peer, new ErrorMessage { Error = "Session Superseded" });
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
@ -527,7 +529,7 @@ namespace GameCult.Networking
|
|||
var password = Secret.DecryptString(login.Password, login.Nonce, _security);
|
||||
if (string.IsNullOrWhiteSpace(auth) || string.IsNullOrWhiteSpace(password))
|
||||
{
|
||||
peer.Send(new ErrorMessage { Error = "Credentials Invalid" });
|
||||
SendLegacy(peer, new ErrorMessage { Error = "Credentials Invalid" });
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
@ -538,13 +540,13 @@ namespace GameCult.Networking
|
|||
|
||||
if (userData == null)
|
||||
{
|
||||
peer.Send(new ErrorMessage { Error = isEmail ? "Email Not Found" : "Username Not Found" });
|
||||
SendLegacy(peer, new ErrorMessage { Error = isEmail ? "Email Not Found" : "Username Not Found" });
|
||||
return;
|
||||
}
|
||||
|
||||
if (!Argon2.Verify(userData.PasswordHash, password))
|
||||
{
|
||||
peer.Send(new ErrorMessage { Error = "Password Incorrect" });
|
||||
SendLegacy(peer, new ErrorMessage { Error = "Password Incorrect" });
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
@ -596,7 +598,7 @@ namespace GameCult.Networking
|
|||
var player = _database.GetByIndex<PlayerData>("PlayerId", playerId.ToString("D"));
|
||||
if (player == null)
|
||||
{
|
||||
peer.Send(new ErrorMessage { Error = "Session Not Found" });
|
||||
SendLegacy(peer, new ErrorMessage { Error = "Session Not Found" });
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
@ -619,7 +621,7 @@ namespace GameCult.Networking
|
|||
}
|
||||
|
||||
var nonce = Secret.NewNonce;
|
||||
peer.Send(new LoginSuccessMessage
|
||||
SendLegacy(peer, new LoginSuccessMessage
|
||||
{
|
||||
Nonce = nonce,
|
||||
Session = Secret.EncryptString(token, nonce, _security) ?? Array.Empty<byte>()
|
||||
|
|
@ -636,6 +638,35 @@ namespace GameCult.Networking
|
|||
SendSessionToken(peer, user.PlayerId);
|
||||
}
|
||||
|
||||
private void SendLegacy(NetPeer? peer, Message message)
|
||||
{
|
||||
if (peer == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var user = _users.GetOrAdd(
|
||||
peer.Id,
|
||||
_ => new User { Peer = peer, Transport = new LiteNetLibTransportConnection(peer) });
|
||||
user.Transport ??= new LiteNetLibTransportConnection(peer);
|
||||
user.Transport.SendLegacy(message);
|
||||
}
|
||||
|
||||
private void SendSchema<T>(NetPeer? peer, T message)
|
||||
where T : ICultNetSchemaMessage
|
||||
{
|
||||
if (peer == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var user = _users.GetOrAdd(
|
||||
peer.Id,
|
||||
_ => new User { Peer = peer, Transport = new LiteNetLibTransportConnection(peer) });
|
||||
user.Transport ??= new LiteNetLibTransportConnection(peer);
|
||||
user.Transport.SendSchema(message);
|
||||
}
|
||||
|
||||
private static bool CheckRateLimit(
|
||||
string ip,
|
||||
int maxAttemptsPerMinute,
|
||||
|
|
@ -686,6 +717,11 @@ namespace GameCult.Networking
|
|||
/// </summary>
|
||||
public NetPeer Peer = null!;
|
||||
|
||||
/// <summary>
|
||||
/// Channel-aware LiteNetLib transport adapter for this peer.
|
||||
/// </summary>
|
||||
public LiteNetLibTransportConnection? Transport;
|
||||
|
||||
/// <summary>
|
||||
/// The last reported latency for the peer.
|
||||
/// </summary>
|
||||
|
|
|
|||
|
|
@ -481,6 +481,26 @@ namespace GameCult.Networking.Tests
|
|||
Throws.InvalidOperationException);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void LiteNetLibTransportConnection_TracksInboundFrames()
|
||||
{
|
||||
var payload = CultNetSchemaMessageSerialization.Serialize(new CultNetHelloMessage
|
||||
{
|
||||
RuntimeId = "csharp",
|
||||
RuntimeKind = "csharp",
|
||||
DisplayName = "C#",
|
||||
SupportedMessageVersions = [CultNetSchemaVersions.Hello]
|
||||
});
|
||||
var connection = new LiteNetLibTransportConnection(CultNetTransportProfiles.CreateLiteNetLib("stats-test"));
|
||||
|
||||
var frame = connection.Receive(payload);
|
||||
|
||||
Assert.That(frame.ChannelId, Is.EqualTo("schema"));
|
||||
Assert.That(frame.Payload, Is.EqualTo(payload));
|
||||
Assert.That(connection.Stats.FramesReceived, Is.EqualTo(1));
|
||||
Assert.That(connection.Stats.BytesReceived, Is.EqualTo(payload.Length));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ReconnectPolicy_ExposesPortableDelayContract()
|
||||
{
|
||||
|
|
|
|||
Loading…
Reference in a new issue