using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting.Server; using Microsoft.AspNetCore.Hosting.Server.Features; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using RailEnterprise.Core.Commands; using RailEnterprise.Core.Common; using RailEnterprise.Core.Rail; using RailEnterprise.Core.Simulation; using RailEnterprise.Protocol; using RailEnterprise.Protocol.Client; using RailEnterprise.Protocol.Messages; using RailEnterprise.Server; using RailEnterprise.Tests.Harness; using RailEnterprise.Tests.Scenarios; namespace RailEnterprise.Tests.Server; /// Server in processo su una porta casuale, con un client WebSocket vero. public sealed class ServerFixture : IAsyncDisposable { public WebApplication App { get; } public GameHost Host { get; } public int Port { get; } public string DataDir { get; } public const string Token = "segreto-di-prova"; private ServerFixture(WebApplication app, string dataDir) { App = app; DataDir = dataDir; Host = app.Services.GetRequiredService().Host!; var addresses = app.Services.GetRequiredService().Features.Get()!.Addresses; Port = new Uri(addresses.First()).Port; } public static ServerFixture Start(World world, int tickMs = 1) { string dir = Path.Combine(Path.GetTempPath(), "railenterprise-test-" + Path.GetRandomFileName()); var config = new ServerConfig { Local = true, Token = Token, TickMs = tickMs, AutosaveMinutes = 0, DataDir = dir, LogLevel = "Error" }; var app = ServerProgram.Build(config, [], world, TestData.Data); app.Start(); return new ServerFixture(app, dir); } public Uri WebSocketUri => new($"ws://127.0.0.1:{Port}/ws"); public async ValueTask DisposeAsync() { await App.StopAsync(); await App.DisposeAsync(); try { Directory.Delete(DataDir, true); } catch (IOException) { } } } /// Client di prova: applica i messaggi alla copia locale e raccoglie gli esiti dei comandi. public sealed class TestClient : IAsyncDisposable { public ProtocolClient Connection { get; } public ClientWorld World { get; } = new(TestData.Data); public Dictionary Results { get; } = []; public List Received { get; } = []; public Welcome Welcome { get; private set; } = null!; private TestClient(ProtocolClient connection) => Connection = connection; public static async Task ConnectAsync(ServerFixture server, ulong resume = 0) { var connection = await ProtocolClient.ConnectAsync(server.WebSocketUri); var client = new TestClient(connection); client.Welcome = await connection.HandshakeAsync(new Hello { ClientVersion = "test", Token = ServerFixture.Token, DataHash = TestData.Data.Hash, ResumeSessionId = resume }); client.World.Apply(client.Welcome); return client; } /// Riceve e applica messaggi finché la condizione è vera. public async Task WaitFor(Func condition, string what, int timeoutMs = 60_000) where T : class { using var cts = new CancellationTokenSource(timeoutMs); while (true) { var value = condition(); if (value is not null) return value; IMessage m; try { m = await Connection.ReceiveAsync(cts.Token); } catch (OperationCanceledException) { throw new AssertionException($"tempo scaduto in attesa di: {what}"); } Received.Add(m); if (m is CommandResultMessage r) Results[r.Seq] = r; World.Apply(m); } } public Task WaitUntil(Func condition, string what, int timeoutMs = 60_000) => WaitFor(() => condition() ? (object)true : null, what, timeoutMs).ContinueWith(_ => true); /// Invia un comando e ne attende l'esito. public async Task Do(GameCommand command) { uint seq = await Connection.SendCommandAsync(command); return await WaitFor(() => Results.GetValueOrDefault(seq), $"esito di {command.Type}"); } public async Task Ok(GameCommand command) { var r = await Do(command); Assert.True(r.Ok, $"{command.Type}: {r.Error} {r.Message}"); return r.Created.Length > 0 ? r.Created[0] : -1; } public Task SubscribeAll() => Connection.SendAsync(new Subscribe { X0 = 0, Y0 = 0, X1 = World.Summary!.WidthCells - 1, Y1 = World.Summary.HeightCells - 1, }); public ValueTask DisposeAsync() => Connection.DisposeAsync(); } public static class ServerTests { private static Vec2 K(double x, double y) => new(x * 1000, y * 1000); [Test(Slow = true, Description = "Accettazione F3 (senza grafica): linea con ponte costruita via WebSocket, anteprima identica al server, treno in moto con posizione coerente")] public static void BuildLineWithBridgeOverTheNetworkAndWatchTheTrain() => Run().GetAwaiter().GetResult(); private static async Task Run() { var scenario = ScenarioHelper.Load("valdoria"); await using var server = ServerFixture.Start(scenario.World); await using var client = await TestClient.ConnectAsync(server); var w = client.World; Assert.Equal(160, w.Summary!.WidthCells); await client.SubscribeAll(); int chunks = ((w.Summary.WidthCells + 63) / 64) * ((w.Summary.HeightCells + 63) / 64); await client.WaitUntil(() => w.Chunks.Count == chunks && w.Towns.Count == 3, "terreno e entità"); // il terreno ricevuto è identico a quello del server Assert.Equal(scenario.World.Terrain.ComputeHash(), w.Terrain!.ComputeHash()); int mine = await client.Ok(new BuildStationCommand(K(2.2, 2.6), 2, "Rocca Bruna")); int mill = await client.Ok(new BuildStationCommand(K(10.6, 5.4), 4, "Acciaieria")); int depot = await client.Ok(new BuildDepotCommand(K(2.6, 4.4), "small", "Deposito")); await client.WaitUntil(() => w.Stations.ContainsKey(mill) && w.Depots.ContainsKey(depot), "stazioni nella copia locale"); // anteprima del client = piano del server (il server rifiuta un costo diverso) var valico = new BuildTrackCommand(scenario.Route("valico", w.Company).Polyline, AllowTunnels: false); var preview = w.PreviewTrack(valico); Assert.True(preview.Valid, string.Join("; ", preview.Errors.Select(e => e.Message))); Assert.True(preview.LengthOf(WorkKind.Bridge) > 0, "il tracciato passa il fiume su un ponte"); int edge = await client.Ok(valico with { ExpectedCostCents = preview.TotalCost.Cents }); await client.WaitUntil(() => w.Edges.ContainsKey(edge), "arco del valico"); var info = w.Edges[edge]; Assert.Equal(preview.Samples.Count, info.S.Length); for (int i = 0; i < info.S.Length; i++) { Assert.Equal(preview.Samples[i].TrackM, info.H[i], $"quota del campione {i}"); Assert.Equal((byte)preview.Samples[i].Kind, info.Kinds[i], $"opera del campione {i}"); } var spur = new BuildTrackCommand([K(2.6, 4.4), K(2.92, 4.95)]); var spurPreview = w.PreviewTrack(spur); Assert.True(spurPreview.Valid); await client.Ok(spur with { ExpectedCostCents = spurPreview.TotalCost.Cents }); // un'anteprima sbagliata viene respinta var wrong = await client.Do(new BuildTrackCommand([K(3.0, 1.0), K(4.0, 1.2)], ExpectedCostCents: 1)); Assert.Equal((ushort)CommandError.PreviewMismatch, wrong.Error); await client.Connection.SendAsync(new SetSpeed { Speed = 8 }); await client.WaitUntil(() => w.Edges.Count >= 3 && w.Edges.Values.All(e => e.State == (byte)EdgeState.Active), "cantieri completati", 120_000); var loco = await client.Do(new BuyVehicleCommand("loco_steam_1850", new DepotId(depot), 1)); var wagons = await client.Do(new BuyVehicleCommand("wagon_hopper", new DepotId(depot), 3)); Assert.True(loco.Ok && wagons.Ok); int train = await client.Ok(new ComposeTrainCommand(new DepotId(depot), loco.Created.Concat(wagons.Created).Select(i => new VehicleId(i)).ToList(), "Treno 1")); int line = await client.Ok(new CreateLineCommand("Linea 1", "#e0a526", [new LineStop(new StationId(mine)), new LineStop(new StationId(mill))])); await client.Ok(new AssignTrainCommand(new TrainId(train), new LineId(line))); await client.WaitUntil(() => w.Motions.TryGetValue(train, out var m) && m.Speed > 5, "treno in moto", 120_000); // in pausa: la posizione disegnata dal client coincide con quella del server await client.Connection.SendAsync(new SetSpeed { Speed = 0 }); // la pausa vale da quando il ciclo di gioco ha elaborato SetSpeed (sotto carico può tardare) for (int i = 0; i < 500 && server.Host.Speed != 0; i++) await Task.Delay(10); Assert.Equal((byte)0, server.Host.Speed); long tick; Vec2? head; while (true) { (tick, head) = await server.Host.InvokeAsync(world => (world.Clock.Tick, Projection.HeadPoint(world, world.Trains[train]))); await Task.Delay(60); long again = await server.Host.InvokeAsync(world => world.Clock.Tick); if (again == tick) break; } // in pausa il server rimanda i moti dei treni in marcia ogni 100 ms await client.WaitUntil(() => w.Motions.TryGetValue(train, out var m) && m.Tick == tick, "moto all'ultimo tick", 10_000); var drawn = w.TrainHead(train); Assert.True(drawn is not null && head is not null); double gap = Vec2.Distance(drawn!.Value, head!.Value); Assert.True(gap < w.Summary.CellSizeM, $"scarto tra client e server {gap:F2} m"); Assert.True(gap < 0.01, $"scarto atteso nullo, misurato {gap:F4} m"); Assert.True(client.Received.OfType().Any(), "resoconti giornalieri ricevuti"); } [Test(Description = "F4 in rete: riepilogo di manutenzione nei record, cartella, registro officina e registro impieghi su richiesta")] public static void MaintenanceDetailsOnRequest() => RunDetails().GetAwaiter().GetResult(); private static async Task RunDetails() { var scenario = ScenarioHelper.Load("valdoria"); await using var server = ServerFixture.Start(scenario.World, tickMs: 50); await using var client = await TestClient.ConnectAsync(server); var w = client.World; await client.WaitFor(() => client.Received.OfType().FirstOrDefault(), "snapshot"); int depot = await client.Ok(new BuildDepotCommand(K(13.2, 5.4), "medium", "Officina di Valdoria")); var loco = await client.Do(new BuyVehicleCommand("loco_steam_1850", new DepotId(depot), 1)); var wagon = await client.Do(new BuyVehicleCommand("wagon_box", new DepotId(depot), 1)); int train = await client.Ok(new ComposeTrainCommand(new DepotId(depot), loco.Created.Concat(wagon.Created).Select(i => new VehicleId(i)).ToList(), "Treno 1")); await client.WaitUntil(() => w.Trains.ContainsKey(train) && w.Depots.ContainsKey(depot), "treno e officina nella copia locale"); Assert.Equal((byte)100, w.Trains[train].Condition); Assert.Equal("inspection", w.Trains[train].NextIntervention); Assert.Equal(4, w.Depots[depot].Stalls); Assert.Equal(TestData.Data.Maintenance.Depots.InitialSpareParts, w.Depots[depot].SpareParts); await client.Connection.SendAsync(new RequestDetail { Kind = DetailKind.TrainCard, Target = train }); var card = await client.WaitFor(() => w.Cards.GetValueOrDefault(train), "cartella di manutenzione"); Assert.Equal(2, card.Vehicles.Count); Assert.Equal(4, card.Vehicles[0].Components.Count); Assert.Equal("engine", card.Vehicles[0].Components[0].Component); Assert.Equal((byte)1, card.Policy); await client.Ok(new ScheduleServiceCommand(new TrainId(train), "service")); await client.Connection.SendAsync(new RequestDetail { Kind = DetailKind.Workshop, Target = depot }); var register = await client.WaitFor(() => w.Workshops.GetValueOrDefault(depot), "registro officina"); Assert.Equal(4, register.Stalls); Assert.Equal(1, register.Jobs.Count); Assert.Equal("service", register.Jobs[0].Intervention); await client.WaitUntil(() => w.Trains[train].Maintenance == TrainMaintenanceStatus.InWorkshop, "treno in officina nel riepilogo"); await client.Connection.SendAsync(new RequestDetail { Kind = DetailKind.Employment, Target = 0 }); var report = await client.WaitFor(() => w.Employment, "registro degli impieghi"); var row = report.Rows.FirstOrDefault(r => r.Kind == 1 && r.Industry == depot); Assert.True(row is not null, "l'officina compare nel registro"); Assert.Equal(16, row!.JobsStaff); // dettagli di entità altrui o inesistenti: nessuna risposta, nessun errore await client.Connection.SendAsync(new RequestDetail { Kind = DetailKind.TrainCard, Target = 999 }); await client.Connection.SendAsync(new Ping { Nonce = 5 }); await client.WaitFor(() => client.Received.OfType().FirstOrDefault(p => p.Nonce == 5), "il server risponde ancora"); } [Test(Description = "Hello con token errato, dati diversi o protocollo vecchio riceve Reject")] public static void HandshakeRejections() => RunRejections().GetAwaiter().GetResult(); private static async Task RunRejections() { await using var server = ServerFixture.Start(TestWorlds.Small(301), tickMs: 50); async Task Try(Hello hello) { await using var c = await ProtocolClient.ConnectAsync(server.WebSocketUri); try { await c.HandshakeAsync(hello); return null; } catch (SessionRejectedException e) { return e.Reject.Code; } } Assert.Equal(RejectCode.BadToken, await Try(new Hello { Token = "sbagliato" })); Assert.Equal(RejectCode.DataMismatch, await Try(new Hello { Token = ServerFixture.Token, DataHash = 1 })); Assert.Equal(RejectCode.ProtocolVersion, await Try(new Hello { Token = ServerFixture.Token, ProtocolVersion = 999 })); Assert.Equal((RejectCode?)null, await Try(new Hello { Token = ServerFixture.Token })); } [Test(Description = "Ping, salvataggi, ripresa della sessione e API HTTP")] public static void PingSavesResumeAndHttp() => RunMisc().GetAwaiter().GetResult(); private static async Task RunMisc() { await using var server = ServerFixture.Start(TestWorlds.Small(302), tickMs: 50); ulong sessionId; await using (var client = await TestClient.ConnectAsync(server)) { sessionId = client.Welcome.SessionId; await client.Connection.SendAsync(new Ping { Nonce = 41 }); var pong = await client.WaitFor(() => client.Received.OfType().FirstOrDefault(), "pong"); Assert.Equal(41UL, pong.Nonce); await client.Connection.SendAsync(new Save { Name = "prova rete" }); var list = await client.WaitFor(() => client.Received.OfType().FirstOrDefault(), "elenco dei salvataggi"); Assert.Equal(1, list.Saves.Count); Assert.True(list.Saves[0].SaveId.StartsWith("prova_rete-", StringComparison.Ordinal), list.Saves[0].SaveId); await client.WaitFor(() => client.Received.OfType().FirstOrDefault(), "snapshot"); } // ripresa con lo stesso id: stessa sessione, stato rimandato per intero await using (var again = await TestClient.ConnectAsync(server, resume: sessionId)) { Assert.Equal(sessionId, again.Welcome.SessionId); await again.WaitFor(() => again.Received.OfType().FirstOrDefault(), "snapshot dopo la ripresa"); } using var http = new HttpClient { BaseAddress = new Uri($"http://127.0.0.1:{server.Port}") }; Assert.Equal("ok", await http.GetStringAsync("/health")); string metrics = await http.GetStringAsync("/metrics"); foreach (string name in new[] { "tick_ms", "trains", "packets", "contracts", "sessions" }) Assert.True(metrics.Contains($"\n{name} ", StringComparison.Ordinal), $"metrica {name}"); var posted = await http.PostAsync("/api/saves?name=da-http", null); Assert.Equal(System.Net.HttpStatusCode.Created, posted.StatusCode); string saves = await http.GetStringAsync("/api/saves"); Assert.True(saves.Contains("da-http", StringComparison.Ordinal), saves); string id = saves.Split("\"id\":\"")[1].Split('"')[0]; var file = await http.GetByteArrayAsync($"/api/saves/{id}"); Assert.True(file.AsSpan(0, 4).SequenceEqual("RESV"u8)); } }