F3: protocollo binario completo, server con WebSocket e immagine Docker

- 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
This commit is contained in:
Claude committed 2026-10-02 00:14:13 +00:00
1 parent ac9414a03d
commit 5a318e6528
36 files changed
+4940 -62

No files matched your search

@@ -182,7 +182,7 @@ public static class EconomyTests
{
var w = TestWorlds.Small(108);
ulong before = ViaFerrea.Core.Persistence.StateHasher.Compute(w);
w.Enqueue(new PendingCommand(CommandType.BuildTrack, []) { Issuer = w.Player.Id, Seq = 9 });
w.Enqueue(new OverhaulIndustryCommand(new IndustryId(0)) { Issuer = w.Player.Id, Seq = 9 });
w.Enqueue(new TakeLoanCommand(Money.FromLire(1)) { Issuer = new CompanyId(99), Seq = 10 });
w.Pipeline.Get<CommandSystem>().Step(w.Context);
var results = w.DrainResults();
@@ -0,0 +1,283 @@
using ViaFerrea.Core.Commands;
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Economy;
using ViaFerrea.Core.Rail;
using ViaFerrea.Protocol;
using ViaFerrea.Protocol.Messages;
using ViaFerrea.Tests.Harness;
namespace ViaFerrea.Tests.Protocol;
public static class ProtocolTests
{
private static readonly Vec2 P = new(1234.5, 6789.25);
/// <summary>Un esemplare con campi non predefiniti per ogni messaggio del protocollo.</summary>
public static IEnumerable<IMessage> SampleMessages()
{
yield return new Hello { ClientVersion = "0.1.0", Token = "segreto", ResumeSessionId = 42, DataHash = 0xDEADBEEFUL };
yield return new Ping { Nonce = 7 };
yield return new Subscribe { X0 = -3, Y0 = 4, X1 = 300, Y1 = 200, Lod = 1 };
yield return new CommandMessage { Seq = 99, Command = new BuildStationCommand(P, 3, "Stazione Nord") };
yield return new SetSpeed { Speed = 4 };
yield return new ListSaves();
yield return new Save { Name = "partita è bella" };
yield return new Load { SaveId = "auto-0003" };
yield return new NewGame { Seed = 123, SizeKm = 128, StartYear = 1860, DifficultyPreset = "personalizzata", Overrides = [("wearMultiplier", 1.3), ("aiCompetitors", 2)], EndlessFlags = 0x7F };
yield return new Welcome
{
SessionId = 77,
Summary = new WorldSummary
{
Seed = 5, SizeKm = 64, StartYear = 1850, Tick = 1000, Date = "3 gennaio 1850", CompanyId = 0, CompanyName = "Società",
RegionId = "valdoria", WidthCells = 640, HeightCells = 640, CellSizeM = 100, ChunkCells = 64, Speed = 1, TerrainHash = 99,
},
DataHash = 12345,
Difficulty = "imprenditore",
};
yield return new Reject { Code = RejectCode.BadToken, Reason = "Token errato" };
yield return new Pong { Nonce = 7, ServerTick = 123456 };
yield return SampleChunk();
yield return new EntitySnapshot { Tick = 55, Entities = SampleEntities() };
yield return new EntityDelta { Tick = 56, Changed = SampleEntities(), Removed = [(EntityType.Train, 3), (EntityType.Station, 9)] };
yield return new TrackWorks { Edges = [SampleEdge()], Removed = [4, 5] };
yield return new TrainMotion
{
TrainId = 12, Tick = 999, State = 2, Condition = 87.5f, Speed = 13.4f, LengthM = 71, HeadDistance = 120.5,
Segments = [new MotionSegment(3, true, 10, 300), new MotionSegment(4, false, 500, 0)],
};
yield return new DailyDigest
{
Day = 31, Tick = 7440, Date = "1 febbraio 1850", Cash = new Money(123456789), NetWorth = new Money(-5), Rating = "BBB",
Prices = [new Money(3800), new Money(4200)], Events = [SampleEvent()], StateHash = 0xABCDEF, Slow = true, Speed = 2, TickMs = 0.84f,
};
yield return new MaintenanceAlert { Train = 12, Component = "brakes", Condition = 35, DueDays = 4, Text = "Treno 12: freni al 35 %" };
yield return new EmploymentReport
{
Day = 60,
Rows =
[
new EmploymentRow
{
Industry = 2, JobsWorkers = 40, JobsStaff = 2, WorkersPresent = 39.5f, StaffPresent = 2, Reason = "capacità delle carrozze insufficiente",
Sources = [new EmploymentSource { Town = 1, HomeStation = 3, Line = 1, Category = 0, Headcount = 28, Coverage = 0.97f }],
},
],
};
yield return new MarketTape
{
Day = 90,
Shares = [new SharePrice { Company = 1, Price = new Money(1234), Change = -0.02f, Listed = true }],
Bids = [new BidInfo { Bid = 1, Bidder = 2, Target = 0, PricePerShare = new Money(1500), TargetShare = 0.51, ExpiresDay = 180 }],
};
yield return new CommandResultMessage { Seq = 99, Type = (ushort)CommandType.BuildTrack, Error = 10, Message = "Pendenza eccessiva", Created = [1, 2, 3], Tick = 4000 };
yield return new Notification { Event = SampleEvent() };
yield return new Newspaper { Day = 30, Title = "La Cronaca di Valdoria", Articles = [("Nuova linea", "Inaugurata la linea per il valico."), ("Prezzi", "Il carbone sale.")] };
yield return new SaveList { Saves = [new SaveInfo { SaveId = "s1", Name = "Prima", GameDate = "1 marzo 1851", SizeBytes = 4096, SavedUnixMs = 1_700_000_000_000, Autosave = true }] };
}
private static EventInfo SampleEvent() => new()
{
Day = 31, Kind = 4, Severity = 2, Text = "Treno 12 è fermo da 20 giorni", Entity = 6, EntityIndex = 12, Company = 0,
};
private static MapChunk SampleChunk()
{
int w = 7, h = 5;
var heights = new ushort[w * h];
var types = new byte[w * h];
var river = new byte[w * h];
for (int i = 0; i < heights.Length; i++)
{
heights[i] = (ushort)(i * 997 % 65535);
types[i] = (byte)(i % 11);
river[i] = (byte)(i % 5);
}
return new MapChunk { Cx = 2, Cy = 3, Width = w, Height = h, Heights = heights, Types = types, RiverWidth = river };
}
private static EdgeInfo SampleEdge() => new()
{
Id = 4, Owner = 0, A = 1, B = 2, TrackClass = 1, DoubleTrack = true, Electrified = false, State = 1, Condition = 92, StructureCondition = 100, Progress = 0.4f,
S = [0, 25, 50], X = [0, 25, 50.5], Y = [10, 10, 11], H = [100, 101.25, 102.5], Ground = [100, 99, 103], Kinds = [0, 3, 1], SpeedLimitKmh = [60, 60, 45.5],
Signals = [12.5],
};
private static EntityLists SampleEntities() => new()
{
Companies = [new CompanyInfo { Id = 0, Name = "Società", Color = "#b3573e", IsPlayer = true, Cash = new Money(100), NetWorth = new Money(200), Rating = "A", Tier = 2 }],
Towns = [new TownInfo { Id = 0, Name = "Valdoria", Position = P, Population = 12400, RadiusCells = 4.5, Satisfaction = 0.6f, Services = 3 }],
Industries = [new IndustryInfo { Id = 1, Type = "steel_mill", Name = "Acciaieria", Position = P, FootprintCells = 4, Level = 2, Efficiency = 0.83f, Condition = 97, Owner = -1 }],
Hubs = [new HubInfo { Id = 0, Kind = "port", Name = "Porto", Position = P }],
Nodes = [new NodeInfo { Id = 3, Position = P, HeightM = 120.5, Owner = 0, Station = 1, Depot = -1, Edges = [1, 4] }],
Stations = [new StationInfo { Id = 1, Owner = 0, Name = "Acciaieria", Node = 3, Position = P, Platforms = 4, WaitingUnits = 30, Industries = [1], Towns = [0] }],
Depots = [new DepotInfo { Id = 0, Owner = 0, Name = "Deposito", Node = 5, Position = P, Size = "small" }],
Lines = [new LineInfo { Id = 0, Owner = 0, Name = "Linea 1", Color = "#e0a526", Stops = [new LineStop(new StationId(1)), new LineStop(new StationId(2), WaitFull: true, MaxWaitDays: 2)] }],
Vehicles = [new VehicleInfo { Id = 7, Owner = 0, Type = "wagon_hopper", Depot = -1, Train = 2, Condition = 99.5f }],
Trains = [new TrainInfo { Id = 2, Owner = 0, Name = "Treno 12", Line = 0, State = 3, Vehicles = [6, 7], MaxSpeedKmh = 60, LengthM = 27, Load = 20, Capacity = 20 }],
};
/// <summary>Un esemplare per ogni tipo di comando, con campi non predefiniti.</summary>
public static IEnumerable<GameCommand> SampleCommands()
{
yield return new BuildTrackCommand([P, P + new Vec2(1000, 0), P + new Vec2(2000, 500)], 1.5, false, true, "c100", true, true, 123456);
yield return new RenewTrackCommand(new EdgeId(3));
yield return new UpgradeTrackCommand(new EdgeId(3), "c160", true, true);
yield return new DemolishCommand(DemolishTarget.Signal, 8);
yield return new BuildStationCommand(P, 4);
yield return new BuildDepotCommand(P, "medium", "Officina");
yield return new PlaceSignalCommand(new EdgeId(2), 812.5);
yield return new BuyVehicleCommand("loco_steam_1850", new DepotId(1), 2);
yield return new SellVehicleCommand(new VehicleId(9));
yield return new ComposeTrainCommand(new DepotId(1), [new VehicleId(1), new VehicleId(2)], "Treno 1");
yield return new CreateLineCommand("Linea 1", "#4f7cac", [new LineStop(new StationId(1), true, false, true, 3), new LineStop(new StationId(2))]);
yield return new EditLineCommand(new LineId(1), [new LineStop(new StationId(2))]);
yield return new AssignTrainCommand(new TrainId(4), LineId.None);
yield return new SendToDepotCommand(new TrainId(4), new DepotId(0));
yield return new SetReserveCommand(new TrainId(4), true);
yield return new SetMaintenancePolicyCommand(MaintenanceScope.Line, 2, "thorough");
yield return new ScheduleServiceCommand(new TrainId(4), "overhaul");
yield return new OrderPartsCommand(new DepotId(1), 30);
yield return new TakeLoanCommand(Money.FromLire(50000));
yield return new RepayLoanCommand(new LoanId(1), new Money(999));
yield return new AcceptAgreementCommand(new AgreementId(5));
yield return new RejectAgreementCommand(new AgreementId(6));
yield return new BuyGoodsCommand(new StationId(1), "coal", 100, new Money(4000));
yield return new SellGoodsCommand(new StationId(2), "steel", 50, new Money(15000));
yield return new BuyIndustryCommand(new IndustryId(3), Money.FromLire(1_000_000));
yield return new SetIndustryPolicyCommand(new IndustryId(3), IndustryBudget.High);
yield return new OverhaulIndustryCommand(new IndustryId(3));
yield return new UpgradeIndustryCommand(new IndustryId(3));
yield return new IpoCommand(0.3);
yield return new BuySharesCommand(new CompanyId(2), 10_000, new Money(1500));
yield return new SellSharesCommand(new CompanyId(2), 5_000, new Money(1400));
yield return new PayDividendCommand(new Money(12));
yield return new LaunchBidCommand(new CompanyId(1), new Money(2000), 0.51);
yield return new RespondBidCommand(new BidId(1), false);
yield return new BuyConcessionCommand(new RegionId(2));
yield return new AcceptContractCommand(new ContractId(8));
yield return new FundResearchCommand("electric_traction", Money.FromLire(20000));
yield return new DelegateRegionCommand(new RegionId(1), "crescita", Money.FromLire(500000));
}
[Test(Description = "Ogni messaggio del protocollo ha un esemplare e sopravvive a codifica e decodifica byte per byte")]
public static void EveryMessageRoundTrips()
{
var seen = new HashSet<MessageId>();
foreach (var m in SampleMessages())
{
byte[] frame = Frame.Encode(m);
var decoded = Frame.Decode(frame);
Assert.Equal(m.GetType(), decoded.GetType());
Assert.Equal(m.Id, decoded.Id);
Assert.True(frame.AsSpan().SequenceEqual(Frame.Encode(decoded)), $"{m.Id}: i byte ricodificati differiscono");
seen.Add(m.Id);
}
foreach (var id in Enum.GetValues<MessageId>()) Assert.True(seen.Contains(id), $"manca l'esemplare di {id}");
}
[Test(Description = "Ogni tipo di comando sopravvive al round-trip dentro un messaggio Command")]
public static void EveryCommandRoundTrips()
{
var seen = new HashSet<CommandType>();
foreach (var c in SampleCommands())
{
var message = new CommandMessage { Seq = 17, Command = c };
byte[] frame = Frame.Encode(message);
var decoded = (CommandMessage)Frame.Decode(frame);
Assert.Equal(c.GetType(), decoded.Command.GetType());
Assert.Equal(17u, decoded.Command.Seq);
Assert.True(frame.AsSpan().SequenceEqual(Frame.Encode(decoded)), $"{c.Type}: i byte ricodificati differiscono");
seen.Add(c.Type);
}
foreach (var t in Enum.GetValues<CommandType>()) Assert.True(seen.Contains(t), $"manca l'esemplare del comando {t}");
}
[Test]
public static void FieldsSurviveTheRoundTrip()
{
var track = (BuildTrackCommand)((CommandMessage)Frame.Decode(Frame.Encode(new CommandMessage { Seq = 1, Command = SampleCommands().First() }))).Command;
Assert.Equal(3, track.Polyline.Count);
Assert.Equal(P, track.Polyline[0]);
Assert.Equal("c100", track.TrackClass);
Assert.True(track.DoubleTrack && track.Electrified && !track.AllowBridges);
Assert.Equal(123456L, track.ExpectedCostCents);
var chunk = (MapChunk)Frame.Decode(Frame.Encode(SampleChunk()));
Assert.True(chunk.Heights.AsSpan().SequenceEqual(SampleChunk().Heights));
Assert.True(chunk.RiverWidth.AsSpan().SequenceEqual(SampleChunk().RiverWidth));
var hello = (Hello)Frame.Decode(Frame.Encode(SampleMessages().OfType<Hello>().First()));
Assert.Equal(Frame.ProtocolVersion, hello.ProtocolVersion);
Assert.Equal("segreto", hello.Token);
var delta = (EntityDelta)Frame.Decode(Frame.Encode(SampleMessages().OfType<EntityDelta>().First()));
Assert.Equal((EntityType.Station, 9), delta.Removed[1]);
Assert.Equal("Treno 12", delta.Changed.Trains[0].Name);
Assert.True(delta.Changed.Lines[0].Stops[1].WaitFull);
}
[Test(Description = "Frame troncati o corrotti producono solo ProtocolException")]
public static void TruncatedAndCorruptedFramesFailCleanly()
{
var rng = new Rng(2024);
foreach (var m in SampleMessages())
{
byte[] frame = Frame.Encode(m);
for (int cut = 0; cut < frame.Length; cut += Math.Max(1, frame.Length / 17))
{
byte[] part = frame.AsSpan(0, cut).ToArray();
Assert.Throws<ProtocolException>(() => Frame.Decode(part), $"{m.Id} troncato a {cut}");
}
for (int k = 0; k < 40; k++)
{
byte[] bad = (byte[])frame.Clone();
int at = Frame.HeaderSize + rng.NextInt(Math.Max(1, bad.Length - Frame.HeaderSize));
if (at >= bad.Length) continue;
bad[at] ^= (byte)(1 + rng.NextInt(255));
try
{
Frame.Decode(bad);
}
catch (ProtocolException)
{
}
}
}
// un messaggio sconosciuto e una lunghezza incoerente
Assert.Throws<ProtocolException>(() => Frame.Decode([2, 0, 0, 0, 0xE7, 0x03]));
Assert.Throws<ProtocolException>(() => Frame.Decode([9, 0, 0, 0, 2, 0, 1]));
}
[Test(Description = "Un lettore ignora i byte di estensione che non conosce (campi futuri in coda)")]
public static void ReadersIgnoreUnknownTrailingFields()
{
byte[] frame = Frame.Encode(new Ping { Nonce = 5 });
byte[] longer = new byte[frame.Length + 3];
frame.CopyTo(longer, 0);
longer[frame.Length - 1] = 1; // flags: un blocco opzionale segue
longer[frame.Length] = 0xAA;
System.Buffers.Binary.BinaryPrimitives.WriteUInt32LittleEndian(longer, (uint)(longer.Length - 4));
var ping = (Ping)Frame.Decode(longer);
Assert.Equal(5UL, ping.Nonce);
}
[Test]
public static void VarUIntAndStringsEncodeCompactly()
{
var w = new SpanWriter(8);
w.VarUInt(0);
w.VarUInt(127);
w.VarUInt(128);
w.VarUInt(ulong.MaxValue);
w.String("città");
var r = new SpanReader(w.ToArray());
Assert.Equal(0UL, r.VarUInt());
Assert.Equal(127UL, r.VarUInt());
Assert.Equal(128UL, r.VarUInt());
Assert.Equal(ulong.MaxValue, r.VarUInt());
Assert.Equal("città", r.String());
Assert.Equal(0, r.Remaining);
Assert.Equal(1 + 1 + 2 + 10 + 1 + 6, w.Length);
}
}
+272
View File
@@ -0,0 +1,272 @@
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Hosting.Server.Features;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using ViaFerrea.Core.Commands;
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Rail;
using ViaFerrea.Core.Simulation;
using ViaFerrea.Protocol;
using ViaFerrea.Protocol.Client;
using ViaFerrea.Protocol.Messages;
using ViaFerrea.Server;
using ViaFerrea.Tests.Harness;
using ViaFerrea.Tests.Scenarios;
namespace ViaFerrea.Tests.Server;
/// <summary>Server in processo su una porta casuale, con un client WebSocket vero.</summary>
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<HostHolder>().Host!;
var addresses = app.Services.GetRequiredService<IServer>().Features.Get<IServerAddressesFeature>()!.Addresses;
Port = new Uri(addresses.First()).Port;
}
public static ServerFixture Start(World world, int tickMs = 1)
{
string dir = Path.Combine(Path.GetTempPath(), "viaferrea-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)
{
}
}
}
/// <summary>Client di prova: applica i messaggi alla copia locale e raccoglie gli esiti dei comandi.</summary>
public sealed class TestClient : IAsyncDisposable
{
public ProtocolClient Connection { get; }
public ClientWorld World { get; } = new(TestData.Data);
public Dictionary<uint, CommandResultMessage> Results { get; } = [];
public List<IMessage> Received { get; } = [];
public Welcome Welcome { get; private set; } = null!;
private TestClient(ProtocolClient connection) => Connection = connection;
public static async Task<TestClient> 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;
}
/// <summary>Riceve e applica messaggi finché la condizione è vera.</summary>
public async Task<T> WaitFor<T>(Func<T?> 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<bool> WaitUntil(Func<bool> condition, string what, int timeoutMs = 60_000) =>
WaitFor(() => condition() ? (object)true : null, what, timeoutMs).ContinueWith(_ => true);
/// <summary>Invia un comando e ne attende l'esito.</summary>
public async Task<CommandResultMessage> Do(GameCommand command)
{
uint seq = await Connection.SendCommandAsync(command);
return await WaitFor(() => Results.GetValueOrDefault(seq), $"esito di {command.Type}");
}
public async Task<int> 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 });
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<DailyDigest>().Any(), "resoconti giornalieri ricevuti");
}
[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<RejectCode?> 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<Pong>().FirstOrDefault(), "pong");
Assert.Equal(41UL, pong.Nonce);
await client.Connection.SendAsync(new Save { Name = "prova rete" });
var list = await client.WaitFor(() => client.Received.OfType<SaveList>().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<EntitySnapshot>().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<EntitySnapshot>().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("VFSV"u8));
}
}