Harden CultLib for local production use

This commit is contained in:
Meta Vens 2026-05-09 11:45:46 +01:00
commit 3f1cb8b36e
12 changed files with 1376 additions and 47 deletions

View file

@ -1,5 +1,6 @@
using System;
using System.Collections.Concurrent;
using System.Security.Cryptography;
using GameCult.Logging;
using LiteNetLib;
using MessagePack;
@ -7,6 +8,27 @@ using R3;
namespace GameCult.Networking
{
/// <summary>
/// Describes the client's reconnect posture.
/// </summary>
public enum ClientReconnectState
{
/// <summary>
/// The client is connected or otherwise not trying to reconnect.
/// </summary>
Idle,
/// <summary>
/// The client is waiting for the next reconnect attempt.
/// </summary>
WaitingToReconnect,
/// <summary>
/// The client is actively attempting a reconnect.
/// </summary>
Reconnecting
}
/// <summary>
/// Provides client-side connection, authentication, and message dispatch logic.
/// </summary>
@ -16,6 +38,10 @@ namespace GameCult.Networking
/// Raised when the client encounters a user-visible error.
/// </summary>
public event Action<string>? OnError; // Hook for important user-facing feedback (e.g. via modal UI element)
/// <summary>
/// Raised when reconnect state changes.
/// </summary>
public event Action<ClientReconnectState>? OnReconnectStateChanged;
private NetManager? _client;
private NetPeer? _peer;
private IDisposable? _pollSubscription;
@ -23,6 +49,7 @@ namespace GameCult.Networking
private bool _disposed;
private bool _manualDisconnect;
private bool _isReconnecting;
private int _reconnectAttemptCount;
private readonly ConcurrentDictionary<Type, Delegate> _messageDelegates = new();
@ -31,7 +58,9 @@ namespace GameCult.Networking
private int _lastPort;
private readonly ClientSecurityOptions _security;
private ILogger _logger = new NullLogger();
private static readonly TimeSpan ReconnectDelay = TimeSpan.FromSeconds(1);
private static readonly TimeSpan BaseReconnectDelay = TimeSpan.FromSeconds(1);
private static readonly TimeSpan MaxReconnectDelay = TimeSpan.FromSeconds(30);
private static readonly TimeSpan MaxReconnectJitter = TimeSpan.FromMilliseconds(250);
/// <summary>
/// Gets or sets the logger used by the client.
@ -47,6 +76,16 @@ namespace GameCult.Networking
/// </summary>
public int Ping { get; private set; }
/// <summary>
/// Gets the current reconnect posture exposed to consumers.
/// </summary>
public ClientReconnectState ReconnectState { get; private set; } = ClientReconnectState.Idle;
/// <summary>
/// Gets or sets whether raw payload bodies may be logged for diagnostics.
/// </summary>
public bool LogSensitivePayloads { get; set; }
/// <summary>
/// Gets a value indicating whether the client currently has a verified session.
/// </summary>
@ -83,7 +122,14 @@ namespace GameCult.Networking
{
if (Verified || m is LoginMessage || m is RegisterMessage || m is VerifyMessage)
{
Logger.LogDebug($"Sending message {MessagePackSerializer.SerializeToJson(m)}");
if (LogSensitivePayloads)
{
Logger.LogDebug($"Sending message {MessagePackSerializer.SerializeToJson(m)}");
}
else
{
Logger.LogDebug($"Sending message {typeof(T).Name}");
}
_peer.Send(m);
}
else Logger.LogError("Cannot send, client is not verified!");
@ -192,6 +238,11 @@ namespace GameCult.Networking
/// <param name="host">The remote host name or IP address.</param>
/// <param name="port">The remote server port.</param>
public void Connect(string host = "localhost", int port = 3075)
{
ConnectCore(host, port, resetReconnectBackoff: true);
}
private void ConnectCore(string host, int port, bool resetReconnectBackoff)
{
if (_disposed)
{
@ -200,6 +251,11 @@ namespace GameCult.Networking
_manualDisconnect = false;
_isReconnecting = false;
if (resetReconnectBackoff)
{
_reconnectAttemptCount = 0;
}
SetReconnectState(ClientReconnectState.Idle);
_reconnectSubscription?.Dispose();
_reconnectSubscription = null;
_lastHost = host;
@ -221,8 +277,15 @@ namespace GameCult.Networking
try
{
var bytes = reader.GetRemainingBytes();
Logger.LogDebug($"Received message: {MessagePackSerializer.ConvertToJson(new ReadOnlyMemory<byte>(bytes))}");
var message = MessageSerialization.Deserialize<Message>(bytes);
if (LogSensitivePayloads)
{
Logger.LogDebug($"Received message: {MessagePackSerializer.ConvertToJson(new ReadOnlyMemory<byte>(bytes))}");
}
else
{
Logger.LogDebug($"Received message {message.GetType().Name}");
}
var type = message.GetType();
switch (message)
@ -252,6 +315,8 @@ namespace GameCult.Networking
{
Logger.LogInfo($"Peer {peer.Address}:{peer.Port} connected.");
_peer = peer;
_reconnectAttemptCount = 0;
SetReconnectState(ClientReconnectState.Idle);
if (Verified)
{
var nonce = Secret.NewNonce;
@ -282,6 +347,7 @@ namespace GameCult.Networking
_manualDisconnect = true;
_reconnectSubscription?.Dispose();
_reconnectSubscription = null;
SetReconnectState(ClientReconnectState.Idle);
DisposeTransport();
}
@ -297,6 +363,7 @@ namespace GameCult.Networking
_manualDisconnect = true;
_reconnectSubscription?.Dispose();
_reconnectSubscription = null;
SetReconnectState(ClientReconnectState.Idle);
DisposeTransport();
}
@ -308,15 +375,19 @@ namespace GameCult.Networking
}
_isReconnecting = true;
_reconnectSubscription = Observable.Timer(ReconnectDelay).Subscribe(_ =>
_reconnectAttemptCount++;
var delay = GetReconnectDelayForAttempt(_reconnectAttemptCount);
SetReconnectState(ClientReconnectState.WaitingToReconnect);
_reconnectSubscription = Observable.Timer(delay).Subscribe(_ =>
{
_isReconnecting = false;
_reconnectSubscription?.Dispose();
_reconnectSubscription = null;
SetReconnectState(ClientReconnectState.Reconnecting);
try
{
Connect(_lastHost, _lastPort);
ConnectCore(_lastHost, _lastPort, resetReconnectBackoff: false);
}
catch (Exception ex)
{
@ -326,6 +397,16 @@ namespace GameCult.Networking
});
}
internal static TimeSpan GetReconnectDelayForAttempt(int attempt)
{
var normalizedAttempt = Math.Max(1, attempt);
var exponentialSeconds = Math.Min(
MaxReconnectDelay.TotalSeconds,
BaseReconnectDelay.TotalSeconds * Math.Pow(2, normalizedAttempt - 1));
var jitterMilliseconds = RandomNumberGenerator.GetInt32((int)MaxReconnectJitter.TotalMilliseconds + 1);
return TimeSpan.FromSeconds(exponentialSeconds) + TimeSpan.FromMilliseconds(jitterMilliseconds);
}
private void DisposeTransport()
{
_pollSubscription?.Dispose();
@ -356,5 +437,16 @@ namespace GameCult.Networking
}
}
}
private void SetReconnectState(ClientReconnectState state)
{
if (ReconnectState == state)
{
return;
}
ReconnectState = state;
OnReconnectStateChanged?.Invoke(state);
}
}
}