using System.Net.WebSockets;
using RailEnterprise.Protocol;
using RailEnterprise.Protocol.Messages;
namespace RailEnterprise.Server;
///
/// Endpoint WebSocket /ws: il primo frame dev'essere un Hello (entro 10 s); poi un task
/// riceve i frame e li passa al ciclo di gioco, un altro svuota la coda d'invio della sessione.
///
public static class SessionEndpoint
{
private static readonly TimeSpan HelloTimeout = TimeSpan.FromSeconds(10);
public static async Task HandleAsync(HttpContext context, GameHost host, ILogger log)
{
if (!context.WebSockets.IsWebSocketRequest)
{
context.Response.StatusCode = StatusCodes.Status400BadRequest;
await context.Response.WriteAsync("Serve una connessione WebSocket");
return;
}
using var socket = await context.WebSockets.AcceptWebSocketAsync();
var buffer = new MemoryStream();
IMessage? first;
using (var helloTimeout = CancellationTokenSource.CreateLinkedTokenSource(context.RequestAborted))
{
helloTimeout.CancelAfter(HelloTimeout);
try
{
first = await ReceiveAsync(socket, buffer, helloTimeout.Token);
}
catch (Exception e) when (e is OperationCanceledException or ProtocolException or WebSocketException)
{
await CloseAsync(socket, WebSocketCloseStatus.PolicyViolation, "Hello mancante o non valido");
return;
}
}
if (first is not Hello hello)
{
await CloseAsync(socket, WebSocketCloseStatus.PolicyViolation, "Il primo messaggio dev'essere Hello");
return;
}
var (session, reject) = await host.OpenSessionAsync(hello);
if (session is null)
{
await socket.SendAsync(Frame.Encode(reject!), WebSocketMessageType.Binary, true, context.RequestAborted);
await CloseAsync(socket, WebSocketCloseStatus.PolicyViolation, reject!.Reason);
log.LogInformation("Sessione rifiutata: {Code} {Reason}", reject.Code, reject.Reason);
return;
}
using var cts = CancellationTokenSource.CreateLinkedTokenSource(context.RequestAborted);
var sending = session.SendLoopAsync(socket, cts.Token);
var status = WebSocketCloseStatus.NormalClosure;
string reason = "fine";
try
{
while (socket.State == WebSocketState.Open && !cts.IsCancellationRequested)
{
var message = await ReceiveAsync(socket, buffer, cts.Token);
if (message is null) break;
host.Receive(session, message);
}
}
catch (ProtocolException e)
{
status = e.Message.Contains("4 MB", StringComparison.Ordinal) ? WebSocketCloseStatus.MessageTooBig : WebSocketCloseStatus.InvalidPayloadData;
reason = e.Message;
log.LogWarning("Sessione {Session}: {Error}", session.Id, e.Message);
}
catch (Exception e) when (e is OperationCanceledException or WebSocketException)
{
}
finally
{
host.Detach(session);
cts.Cancel();
try
{
await sending;
}
catch (Exception)
{
// invio interrotto con la connessione
}
await CloseAsync(socket, status, reason);
}
}
/// Riceve un frame completo (anche frammentato in più parti); null alla chiusura.
private static async Task ReceiveAsync(WebSocket socket, MemoryStream buffer, CancellationToken ct)
{
buffer.SetLength(0);
var chunk = new byte[16 * 1024];
while (true)
{
var result = await socket.ReceiveAsync(chunk, ct);
if (result.MessageType == WebSocketMessageType.Close) return null;
if (result.MessageType != WebSocketMessageType.Binary) throw new ProtocolException("solo messaggi binari");
buffer.Write(chunk, 0, result.Count);
if (buffer.Length > Frame.MaxFrameBytes) throw new ProtocolException("frame oltre 4 MB");
if (result.EndOfMessage) return Frame.Decode(buffer.GetBuffer().AsSpan(0, (int)buffer.Length));
}
}
private static async Task CloseAsync(WebSocket socket, WebSocketCloseStatus status, string reason)
{
try
{
if (socket.State is WebSocketState.Open or WebSocketState.CloseReceived)
{
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(2));
string text = reason.Length > 100 ? reason[..100] : reason;
await socket.CloseAsync(status, text, timeout.Token);
}
}
catch (Exception)
{
// il client se n'è già andato
}
}
}