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:
36 files changed
+4940
-62
No files matched your search
@@ -0,0 +1,213 @@
|
||||
using System.Diagnostics;
|
||||
using ViaFerrea.Core.Commands;
|
||||
using ViaFerrea.Core.Common;
|
||||
using ViaFerrea.Core.Data;
|
||||
using ViaFerrea.Core.Map;
|
||||
using ViaFerrea.Core.Rail;
|
||||
using ViaFerrea.Protocol;
|
||||
using ViaFerrea.Protocol.Client;
|
||||
using ViaFerrea.Protocol.Messages;
|
||||
|
||||
namespace ViaFerrea.Tools.Commands;
|
||||
|
||||
/// <summary>
|
||||
/// smoke: collaudo di un server in esecuzione (locale o in Docker) con un client vero. Trova un
|
||||
/// fiume, costruisce due stazioni, un deposito e un binario con ponte usando l'anteprima del
|
||||
/// client come costo atteso (il server rifiuta se differisce), compra un treno, lo mette in linea
|
||||
/// e verifica che la posizione interpolata dal client coincida con quella inviata dal server
|
||||
/// (scarto < 1 cella sui tratti a velocità costante).
|
||||
/// </summary>
|
||||
public sealed class SmokeCommand : IToolCommand
|
||||
{
|
||||
public string Name => "smoke";
|
||||
|
||||
public string Usage => "smoke --url ws://127.0.0.1:7400/ws [--token <t>] [--timeout 600]";
|
||||
|
||||
public int Run(CommandLine args)
|
||||
{
|
||||
string url = args.String("url", "ws://127.0.0.1:7400/ws");
|
||||
string token = args.String("token", "");
|
||||
int timeout = args.Int("timeout", 600);
|
||||
args.EnsureAllUsed();
|
||||
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(timeout));
|
||||
try
|
||||
{
|
||||
return RunAsync(new Uri(url), token, cts.Token).GetAwaiter().GetResult();
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
Console.Error.WriteLine("smoke: tempo scaduto");
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class Session(ProtocolClient connection, ClientWorld world)
|
||||
{
|
||||
public ProtocolClient Connection { get; } = connection;
|
||||
public ClientWorld World { get; } = world;
|
||||
public Dictionary<uint, CommandResultMessage> Results { get; } = [];
|
||||
public List<TrainMotion> Motions { get; } = [];
|
||||
|
||||
public async Task Until(Func<bool> condition, CancellationToken ct)
|
||||
{
|
||||
while (!condition())
|
||||
{
|
||||
var m = await Connection.ReceiveAsync(ct);
|
||||
if (m is CommandResultMessage r) Results[r.Seq] = r;
|
||||
if (m is TrainMotion tm) Motions.Add(tm);
|
||||
World.Apply(m);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<CommandResultMessage> Do(GameCommand c, CancellationToken ct)
|
||||
{
|
||||
uint seq = await Connection.SendCommandAsync(c, ct);
|
||||
await Until(() => Results.ContainsKey(seq), ct);
|
||||
return Results[seq];
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task<int> RunAsync(Uri url, string token, CancellationToken ct)
|
||||
{
|
||||
var data = GameData.LoadDefault();
|
||||
var clock = Stopwatch.StartNew();
|
||||
await using var connection = await ProtocolClient.ConnectAsync(url, ct);
|
||||
var welcome = await connection.HandshakeAsync(new Hello { ClientVersion = "smoke", Token = token, DataHash = data.Hash }, ct);
|
||||
var s = new Session(connection, new ClientWorld(data));
|
||||
var w = s.World;
|
||||
w.Apply(welcome);
|
||||
var summary = welcome.Summary;
|
||||
Console.WriteLine($"smoke: sessione {welcome.SessionId:x}, mappa {summary.SizeKm} km, {summary.Date}");
|
||||
await connection.SendAsync(new Subscribe { X0 = 0, Y0 = 0, X1 = summary.WidthCells - 1, Y1 = summary.HeightCells - 1 }, ct);
|
||||
int chunks = ((summary.WidthCells + summary.ChunkCells - 1) / summary.ChunkCells) * ((summary.HeightCells + summary.ChunkCells - 1) / summary.ChunkCells);
|
||||
await s.Until(() => w.Chunks.Count == chunks && w.Companies.Count > 0, ct);
|
||||
Console.WriteLine($" terreno ricevuto: {chunks} chunk, hash {w.Terrain!.ComputeHash():x16} (server {summary.TerrainHash:x16})");
|
||||
if (w.Terrain.ComputeHash() != summary.TerrainHash) return Fail("terreno diverso da quello del server");
|
||||
|
||||
// capitale: un prestito per stazioni, deposito, binario e treno (il più grande concesso)
|
||||
for (long lire = 400_000; lire >= 25_000; lire /= 2)
|
||||
{
|
||||
var loan = await s.Do(new TakeLoanCommand(Money.FromLire(lire)), ct);
|
||||
if (!loan.Ok) continue;
|
||||
Console.WriteLine($" prestito di {Money.FromLire(lire)}");
|
||||
break;
|
||||
}
|
||||
await s.Until(() => w.Companies.TryGetValue(summary.CompanyId, out var c) && c.Cash.Cents > 0, ct);
|
||||
var site = FindBridgeSite(w);
|
||||
if (site is null) return Fail("nessun attraversamento di fiume adatto trovato");
|
||||
var (a, b, depotAt) = site.Value;
|
||||
Console.WriteLine($" sito: da ({a.X / 1000:F2}, {a.Y / 1000:F2}) a ({b.X / 1000:F2}, {b.Y / 1000:F2}) km");
|
||||
|
||||
var sa = await s.Do(new BuildStationCommand(a, 2, "Smoke Ovest"), ct);
|
||||
var sb = await s.Do(new BuildStationCommand(b, 2, "Smoke Est"), ct);
|
||||
var sd = await s.Do(new BuildDepotCommand(depotAt, "small", "Smoke Deposito"), ct);
|
||||
if (!sa.Ok || !sb.Ok || !sd.Ok) return Fail($"stazioni: {sa.Message} / {sb.Message} / {sd.Message}");
|
||||
await s.Until(() => w.Stations.ContainsKey(sb.Created[0]) && w.Depots.ContainsKey(sd.Created[0]), ct);
|
||||
|
||||
var main = new BuildTrackCommand([a, b]);
|
||||
var preview = w.PreviewTrack(main);
|
||||
if (!preview.Valid) return Fail("anteprima non valida: " + string.Join("; ", preview.Errors.Select(e => e.Message)));
|
||||
var built = await s.Do(main with { ExpectedCostCents = preview.TotalCost.Cents }, ct);
|
||||
if (!built.Ok) return Fail($"binario: {built.Message}");
|
||||
Console.WriteLine($" binario: {preview.LengthM / 1000:F2} km, ponte {preview.LengthOf(WorkKind.Bridge):F0} m, {preview.TotalCost}, {preview.Days} giorni (anteprima = server)");
|
||||
int edge = built.Created[0];
|
||||
await s.Until(() => w.Edges.ContainsKey(edge), ct);
|
||||
var info = w.Edges[edge];
|
||||
for (int i = 0; i < info.S.Length; i++)
|
||||
{
|
||||
if (info.S.Length != preview.Samples.Count || info.H[i] != preview.Samples[i].TrackM) return Fail($"profilo diverso al campione {i}");
|
||||
}
|
||||
var spur = new BuildTrackCommand([depotAt, a]);
|
||||
var spurPreview = w.PreviewTrack(spur);
|
||||
var spurBuilt = await s.Do(spur with { ExpectedCostCents = spurPreview.Valid ? spurPreview.TotalCost.Cents : 0 }, ct);
|
||||
if (!spurBuilt.Ok) return Fail($"raccordo del deposito: {spurBuilt.Message}");
|
||||
|
||||
await connection.SendAsync(new SetSpeed { Speed = 8 }, ct);
|
||||
await s.Until(() => w.Edges.Values.All(e => e.State == (byte)EdgeState.Active), ct);
|
||||
Console.WriteLine($" cantieri completati: {w.LastDigest?.Date} ({clock.Elapsed.TotalSeconds:F0} s)");
|
||||
|
||||
int depot = sd.Created[0];
|
||||
var loco = await s.Do(new BuyVehicleCommand("loco_steam_1850", new DepotId(depot), 1), ct);
|
||||
var cars = await s.Do(new BuyVehicleCommand("wagon_hopper", new DepotId(depot), 3), ct);
|
||||
if (!loco.Ok || !cars.Ok) return Fail($"acquisto: {loco.Message} / {cars.Message}");
|
||||
var train = await s.Do(new ComposeTrainCommand(new DepotId(depot), loco.Created.Concat(cars.Created).Select(i => new VehicleId(i)).ToList(), "Treno di collaudo"), ct);
|
||||
var line = await s.Do(new CreateLineCommand("Linea di collaudo", "#e0a526", [new LineStop(new StationId(sa.Created[0])), new LineStop(new StationId(sb.Created[0]))]), ct);
|
||||
if (!train.Ok || !line.Ok) return Fail($"treno o linea: {train.Message} / {line.Message}");
|
||||
int trainId = train.Created[0];
|
||||
var assign = await s.Do(new AssignTrainCommand(new TrainId(trainId), new LineId(line.Created[0])), ct);
|
||||
if (!assign.Ok) return Fail(assign.Message);
|
||||
|
||||
// a velocità 1 si confronta la posizione estrapolata dal client con quella del moto successivo
|
||||
await connection.SendAsync(new SetSpeed { Speed = 1 }, ct);
|
||||
var calendar = w.Calendar!;
|
||||
int pairs = 0;
|
||||
double worst = 0;
|
||||
s.Motions.Clear();
|
||||
await s.Until(() =>
|
||||
{
|
||||
var list = s.Motions.Where(m => m.TrainId == trainId).ToList();
|
||||
pairs = 0;
|
||||
worst = 0;
|
||||
for (int i = 1; i < list.Count; i++)
|
||||
{
|
||||
var p = list[i - 1];
|
||||
var q = list[i];
|
||||
if (p.Speed < 1 || Math.Abs(p.Speed - q.Speed) > 0.05 || q.Tick <= p.Tick || q.Tick - p.Tick > 20) continue;
|
||||
var predicted = w.TrainHead(p, (q.Tick - p.Tick) * calendar.TrainSecondsPerTick);
|
||||
var actual = w.PointAlong(q, q.HeadDistance);
|
||||
if (predicted is null || actual is null) continue;
|
||||
worst = Math.Max(worst, Vec2.Distance(predicted.Value, actual.Value));
|
||||
pairs++;
|
||||
}
|
||||
return pairs >= 5;
|
||||
}, ct);
|
||||
Console.WriteLine($" treno {trainId} in moto: {pairs} confronti, scarto massimo {worst:F2} m (limite {summary.CellSizeM:F0} m)");
|
||||
await connection.SendAsync(new SetSpeed { Speed = 1 }, ct);
|
||||
if (worst >= summary.CellSizeM) return Fail("posizione del treno incoerente");
|
||||
Console.WriteLine($"smoke: ok in {clock.Elapsed.TotalSeconds:F0} s");
|
||||
return 0;
|
||||
}
|
||||
|
||||
private static int Fail(string why)
|
||||
{
|
||||
Console.Error.WriteLine($"smoke: FALLITO — {why}");
|
||||
return 1;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Cerca un attraversamento di fiume rettilineo di 1,5–2,5 km con estremità e deposito su
|
||||
/// terreno libero e un'anteprima valida con ponte.
|
||||
/// </summary>
|
||||
private static (Vec2 A, Vec2 B, Vec2 Depot)? FindBridgeSite(ClientWorld w)
|
||||
{
|
||||
var t = w.Terrain!;
|
||||
var rng = new Rng(7);
|
||||
bool Free(Vec2 p)
|
||||
{
|
||||
if (p.X < 2000 || p.Y < 2000 || p.X > t.WidthM - 2000 || p.Y > t.HeightM - 2000) return false;
|
||||
var (x, y) = t.CellAt(p);
|
||||
return (CellType)t.Types[y * t.Width + x] is CellType.Plain or CellType.Field or CellType.Forest or CellType.Hill;
|
||||
}
|
||||
var rivers = new List<int>();
|
||||
for (int i = 0; i < t.RiverWidth.Length; i++)
|
||||
{
|
||||
if (t.RiverWidth[i] > 0) rivers.Add(i);
|
||||
}
|
||||
if (rivers.Count == 0) return null;
|
||||
for (int attempt = 0; attempt < 400; attempt++)
|
||||
{
|
||||
int cell = rivers[rng.NextInt(rivers.Count)];
|
||||
var center = t.CellCenter(cell % t.Width, cell / t.Width);
|
||||
double angle = rng.NextDouble(0, Math.PI);
|
||||
var dir = new Vec2(Math.Cos(angle), Math.Sin(angle));
|
||||
double half = rng.NextDouble(750, 1250);
|
||||
var a = center - dir * half;
|
||||
var b = center + dir * half;
|
||||
var depot = a - dir * 600;
|
||||
if (!Free(a) || !Free(b) || !Free(depot)) continue;
|
||||
var plan = w.PreviewTrack(new BuildTrackCommand([a, b]));
|
||||
if (plan.Valid && plan.LengthOf(WorkKind.Bridge) > 0 && plan.Days <= 120) return (a, b, depot);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,7 @@ public static class ToolsProgram
|
||||
new SimulateCommand(),
|
||||
new ProfileCommand(),
|
||||
new BenchCommand(),
|
||||
new SmokeCommand(),
|
||||
];
|
||||
|
||||
public static int Main(string[] args)
|
||||
|
||||
Reference in new issue
Block a user