- Protocol: SpanWriter/SpanReader, frame [u32][u16][payload], tutti i messaggi dei due versi con byte di estensione, codec di tutti i 38 comandi, test di round-trip, troncamento e corruzione. - Comandi delle fasi successive con formato definitivo (NotImplemented). - ClientWorld e ProtocolClient condivisi da client Godot e test: copia del terreno a chunk, entità, rete con gli stessi id, moto dei treni. - TrackPreview estratto dai comandi: anteprima del client e piano del server con lo stesso codice; stazioni e depositi demoliti esclusi dagli agganci. - Server: GameLoop con accumulatore e velocità effettiva, sessioni con coda a due classi e ripresa, delta per hash, TrackWorks a lotti, moto dei treni nel viewport, resoconti giornalieri, /health, /metrics, /api/saves, autosave a rotazione, log JSON, --local e --healthcheck. - Docker: Dockerfile, compose, modello Unraid; build senza rete. - viaferrea-tools smoke: collaudo end-to-end contro un server in esecuzione. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0191R7vXgtbAvSV4V8tj8uzL
116 lines
5.3 KiB
C#
116 lines
5.3 KiB
C#
using System.Net.Http;
|
|
using System.Text.Json.Serialization;
|
|
using Microsoft.AspNetCore.Hosting.Server;
|
|
using Microsoft.AspNetCore.Hosting.Server.Features;
|
|
using ViaFerrea.Core.Data;
|
|
using ViaFerrea.Core.Simulation;
|
|
using ProtocolSaveInfo = ViaFerrea.Protocol.Messages.SaveInfo;
|
|
|
|
namespace ViaFerrea.Server;
|
|
|
|
/// <summary>
|
|
/// Server autorevole di Via Ferrea: Kestrel con WebSocket su /ws, API HTTP (/health, /metrics,
|
|
/// /api/saves), ciclo di gioco su un thread dedicato, log JSON su stdout.
|
|
/// </summary>
|
|
public static class ServerProgram
|
|
{
|
|
public static int Main(string[] args)
|
|
{
|
|
var config = ServerConfig.From(args, Environment.GetEnvironmentVariables());
|
|
if (config.HealthCheck) return HealthCheck(config);
|
|
using var app = Build(config, args);
|
|
app.Start();
|
|
if (config.Local)
|
|
{
|
|
var addresses = app.Services.GetRequiredService<IServer>().Features.Get<IServerAddressesFeature>()!.Addresses;
|
|
int port = new Uri(addresses.First()).Port;
|
|
Console.Out.WriteLine($"LISTENING {port}");
|
|
Console.Out.Flush();
|
|
}
|
|
app.WaitForShutdown();
|
|
return 0;
|
|
}
|
|
|
|
/// <summary>Costruisce l'applicazione; i test la avviano in processo su una porta casuale.</summary>
|
|
public static WebApplication Build(ServerConfig config, string[]? args = null, World? world = null, GameData? data = null)
|
|
{
|
|
var builder = WebApplication.CreateSlimBuilder(args ?? []);
|
|
builder.Logging.ClearProviders();
|
|
builder.Logging.AddJsonConsole(o =>
|
|
{
|
|
o.IncludeScopes = false;
|
|
o.TimestampFormat = "yyyy-MM-ddTHH:mm:ss.fffZ";
|
|
o.UseUtcTimestamp = true;
|
|
o.JsonWriterOptions = new System.Text.Json.JsonWriterOptions { Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping };
|
|
});
|
|
builder.Logging.SetMinimumLevel(Enum.TryParse<LogLevel>(config.LogLevel, true, out var level) ? level : LogLevel.Information);
|
|
builder.WebHost.UseUrls(config.Local ? "http://127.0.0.1:0" : $"http://0.0.0.0:{config.Port}");
|
|
builder.Services.AddSingleton<HostHolder>();
|
|
builder.Services.ConfigureHttpJsonOptions(o =>
|
|
{
|
|
o.SerializerOptions.TypeInfoResolverChain.Insert(0, ServerJsonContext.Default);
|
|
o.SerializerOptions.Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping;
|
|
});
|
|
|
|
var app = builder.Build();
|
|
var log = app.Services.GetRequiredService<ILoggerFactory>().CreateLogger("ViaFerrea.Server");
|
|
data ??= GameData.LoadDefault();
|
|
log.LogInformation("Dati caricati: hash {Hash:x16}", data.Hash);
|
|
var host = new GameHost(config, data, log, world);
|
|
app.Lifetime.ApplicationStarted.Register(host.Start);
|
|
app.Lifetime.ApplicationStopping.Register(host.Dispose);
|
|
|
|
app.UseWebSockets(new WebSocketOptions { KeepAliveInterval = TimeSpan.FromSeconds(30) });
|
|
app.Map("/ws", context => SessionEndpoint.HandleAsync(context, host, log));
|
|
app.MapGet("/health", () => host.Healthy ? Results.Text("ok") : Results.Text("ciclo di gioco fermo", statusCode: 503));
|
|
app.MapGet("/metrics", () => Results.Text(host.Metrics(), "text/plain; version=0.0.4"));
|
|
app.MapGet("/api/saves", () => Results.Json(host.Saves.List().Select(SaveDto.From).ToList(), Json.ListSaveDto));
|
|
app.MapGet("/api/saves/{id}", (string id) =>
|
|
host.Saves.Exists(id) ? Results.File(host.Saves.PathOf(id), "application/octet-stream", Path.GetFileName(host.Saves.PathOf(id))) : Results.NotFound());
|
|
app.MapPost("/api/saves", async (string? name) =>
|
|
{
|
|
var info = await host.InvokeAsync(_ => host.SaveNow(string.IsNullOrWhiteSpace(name) ? "partita" : name));
|
|
return Results.Json(SaveDto.From(info), Json.SaveDto, statusCode: StatusCodes.Status201Created);
|
|
});
|
|
app.Services.GetRequiredService<HostHolder>().Host = host;
|
|
return app;
|
|
}
|
|
|
|
private static readonly ServerJsonContext Json = new(new System.Text.Json.JsonSerializerOptions
|
|
{
|
|
PropertyNamingPolicy = System.Text.Json.JsonNamingPolicy.CamelCase,
|
|
Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
|
|
});
|
|
|
|
private static int HealthCheck(ServerConfig config)
|
|
{
|
|
try
|
|
{
|
|
using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(4) };
|
|
var response = http.GetAsync($"http://127.0.0.1:{config.Port}/health").GetAwaiter().GetResult();
|
|
return response.IsSuccessStatusCode ? 0 : 1;
|
|
}
|
|
catch (Exception)
|
|
{
|
|
return 1;
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>Riferimento al GameHost per i test in processo.</summary>
|
|
public sealed class HostHolder
|
|
{
|
|
public GameHost? Host { get; set; }
|
|
}
|
|
|
|
/// <summary>Descrizione di un salvataggio nell'API HTTP.</summary>
|
|
public sealed record SaveDto(string Id, string Name, string GameDate, long SizeBytes, long SavedUnixMs, bool Autosave)
|
|
{
|
|
public static SaveDto From(ProtocolSaveInfo s) => new(s.SaveId, s.Name, s.GameDate, s.SizeBytes, s.SavedUnixMs, s.Autosave);
|
|
}
|
|
|
|
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, WriteIndented = false)]
|
|
[JsonSerializable(typeof(SaveDto))]
|
|
[JsonSerializable(typeof(List<SaveDto>))]
|
|
internal sealed partial class ServerJsonContext : JsonSerializerContext;
|