using System.Collections.Concurrent; using System.Net; using System.Net.Sockets; using System.Net.WebSockets; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using Server.Redis; using Server.Services.Auth; using StackExchange.Redis; namespace Server.Networking; public sealed class NetworkManager { private readonly ILogger _log; private readonly MessageRouter _router; private readonly ConcurrentDictionary _connections = new(); private readonly ISessionRegistry _sessions; private readonly IRedisManager _redis; private readonly ISessionAudit _sessionAudit; private readonly TimeSpan _tickInterval; private readonly TimeSpan _idleTimeout; private readonly int _maxConnections; public NetworkManager(ILogger log, MessageRouter router, ISessionRegistry sessions, IRedisManager redis, ISessionAudit sessionAudit) { _log = log; _router = router; _sessions = sessions; _redis = redis; _sessionAudit = sessionAudit; var tickHz = int.TryParse(Environment.GetEnvironmentVariable("TICK_RATE_HZ"), out var hz) ? Math.Clamp(hz, 1, 120) : 20; _tickInterval = TimeSpan.FromMilliseconds(1000.0 / tickHz); _idleTimeout = TimeSpan.FromSeconds(int.TryParse(Environment.GetEnvironmentVariable("IDLE_TIMEOUT_S"), out var idle) ? Math.Clamp(idle, 10, 300) : 45); _maxConnections = int.TryParse(Environment.GetEnvironmentVariable("MAX_CONN"), out var mc) ? Math.Max(mc, 100) : 10_000; _log.LogInformation("Tick={Hz}Hz IdleTimeout={Idle}s MaxConn={Max}", tickHz, _idleTimeout.TotalSeconds, _maxConnections); redis.FlushDatabaseAsync(); } public async Task AcceptWebSocketAsync(HttpContext ctx, WebSocket ws) { if (_connections.Count >= _maxConnections) { await ws.CloseAsync(WebSocketCloseStatus.PolicyViolation, "server full", CancellationToken.None); return; } var conn = new WebSocketConnection(ws, ctx.Connection.RemoteIpAddress == null ? null : new IPEndPoint(ctx.Connection.RemoteIpAddress, ctx.Connection.RemotePort)); _connections[conn.Id] = conn; _log.LogInformation("WS connected {Id} {Remote}", conn.Id, conn.RemoteEndPoint); try { while (conn.IsAlive) { using var cts = new CancellationTokenSource(_idleTimeout); var data = await conn.ReceiveAsync(cts.Token); if (data is null) break; await _router.OnMessageAsync(conn, data.Value, CancellationToken.None); } } catch (OperationCanceledException) { /* idle timeout */ } catch (Exception ex) { _log.LogWarning(ex, "WS loop error {Id}", conn.Id); } finally { await CleanupAsync(conn, "ws closed"); } } public async Task AcceptTcpLoopAsync(TcpListener listener, CancellationToken stopping) { while (!stopping.IsCancellationRequested) { TcpClient? client = null; try { client = await listener.AcceptTcpClientAsync(stopping); if (_connections.Count >= _maxConnections) { client.Close(); continue; } _ = HandleTcpClientAsync(client, stopping); } catch (OperationCanceledException) { break; } catch (Exception ex) { _log.LogError(ex, "TCP accept failed"); client?.Close(); } } } private async Task HandleTcpClientAsync(TcpClient client, CancellationToken ct) { var conn = new TcpConnection(client); _connections[conn.Id] = conn; _log.LogInformation("TCP connected {Id} {Remote}", conn.Id, conn.RemoteEndPoint); try { while (conn.IsAlive && !ct.IsCancellationRequested) { using var idleCts = new CancellationTokenSource(_idleTimeout); var linked = CancellationTokenSource.CreateLinkedTokenSource(idleCts.Token, ct); var data = await conn.ReceiveAsync(linked.Token); if (data is null) break; await _router.OnMessageAsync(conn, data.Value, ct); } } catch (OperationCanceledException) { /* idle timeout or shutdown */ } catch (Exception ex) { _log.LogWarning(ex, "TCP loop error {Id}", conn.Id); } finally { await CleanupAsync(conn, "tcp closed"); } } public async Task RunTickLoopAsync(CancellationToken stopping) { var timer = new PeriodicTimer(_tickInterval); try { while (!stopping.IsCancellationRequested && await timer.WaitForNextTickAsync(stopping)) { await TickAsync(stopping); } } catch (OperationCanceledException) { /* shutting down */ } finally { timer.Dispose(); } } private Task TickAsync(CancellationToken ct) { // Example: prune idle, broadcast heartbeat, step simulation, etc. var now = DateTime.UtcNow; foreach (var (id, conn) in _connections) { if (now - conn.LastSeenUtc > _idleTimeout + TimeSpan.FromSeconds(5)) { _ = CleanupAsync(conn, "idle prune"); } } // TODO: call your simulation step here return Task.CompletedTask; } private async Task CleanupAsync(IConnection conn, string reason) { if (_connections.TryRemove(conn.Id, out _)) { if (_sessions.TryGet(conn.Id, out var accountId, out var token) && accountId != 0 && !string.IsNullOrEmpty(token)) { try { var onlineKey = $"online:acct:{accountId}"; var sessKey = $"sess:{token}"; const string lua = @" if redis.call('GET', KEYS[1]) == ARGV[1] then redis.call('DEL', KEYS[1]) end redis.call('DEL', KEYS[2]) return 1"; await _redis.Db.ScriptEvaluateAsync(lua, new StackExchange.Redis.RedisKey[] { onlineKey, sessKey }, new StackExchange.Redis.RedisValue[] { token }); // NEW: close the SQL session audit row await _sessionAudit.EndAsync(accountId, token, reason); _sessions.Unbind(conn.Id); _log.LogInformation("Logged out account {AccountId} on disconnect", accountId); } catch (Exception ex) { _log.LogWarning(ex, "Failed logout cleanup for account {AccountId}", accountId); try { await _sessionAudit.EndAsync(accountId, token, reason); } catch { } _sessions.Unbind(conn.Id); } } _log.LogInformation("Disconnected {Id} ({Reason})", conn.Id, reason); try { await conn.CloseAsync(reason); } catch { } try { await conn.DisposeAsync(); } catch { } } } }