Infrastruttura: nome «Rail Enterprise», CI e rilasci su Gitea, documentazione
CI / Build e test (pull_request) Successful in 1m20s
CI / Immagine Docker (pull_request) Successful in 37s

Il progetto adotta il nome «Rail Enterprise» ovunque (codice RailEnterprise.*,
variabili RE_*, intestazioni RESV/RECL, immagine rail-enterprise-server) per
allinearsi al repository Gitea. Aggiunge Gitea Actions sul modello di Chronos:
CI su PR e main, rilascio da tag con gioco Windows (client Godot + server in
server/), server Windows/Linux e immagine Docker nel registro Gitea, nightly.
Aggiunge i riferimenti visivi 06–09, i modelli di PR e issue, l'ADR 0014 e
aggiorna README (comandi locali), STATE e CLAUDE.md. 120 test verdi.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-07 11:14:54 +01:00
1 parent f6c2a17b4d
commit c1a0049bcf
300 files changed
+1602 -1045

No files matched your search

+713
View File
@@ -0,0 +1,713 @@
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Globalization;
using System.Security.Cryptography;
using System.Text;
using RailEnterprise.Core.Commands;
using RailEnterprise.Core.Common;
using RailEnterprise.Core.Data;
using RailEnterprise.Core.Simulation;
using RailEnterprise.Protocol;
using RailEnterprise.Protocol.Messages;
namespace RailEnterprise.Server;
/// <summary>
/// Ospita la partita: il mondo appartiene al thread del ciclo di gioco, che esegue i tick con un
/// accumulatore, applica i messaggi delle sessioni (coda concorrente drenata a inizio giro) e
/// pubblica verso i client snapshot, delta, opere, moto dei treni e resoconti giornalieri.
/// Se i tick non stanno nel budget la velocità effettiva si dimezza e il resoconto segnala «slow».
/// </summary>
public sealed class GameHost : IDisposable
{
public static readonly byte[] Speeds = [0, 1, 2, 4, 8];
private const long ResumeWindowMs = 120_000;
private const long MotionIntervalMs = 100;
private const int TrackBatchBytes = 1024 * 1024;
private readonly ServerConfig _config;
private readonly GameData _data;
private readonly ILogger _log;
private readonly SaveStore _saves;
private readonly ConcurrentQueue<Action> _inbox = new();
private readonly Dictionary<ulong, Session> _sessions = [];
private readonly Dictionary<uint, (Session Session, uint ClientSeq)> _pending = [];
private readonly List<EventInfo> _dayEvents = [];
private readonly Stopwatch _clock = Stopwatch.StartNew();
private World _world;
private Thread? _thread;
private volatile bool _stop;
private byte _speed = 1;
private double _effectiveSpeed = 1;
private bool _slow;
private uint _serverSeq;
private long _lastMotionMs;
private long _lastAutosaveMs;
private long _lastHeartbeatMs;
private double _tickMsEma;
private bool _publishDirty;
private bool _dailyDue;
private bool _monthlyDue;
private ulong _lastTerrainHash;
private FileStream? _record;
// istantanee per /metrics (lette da altri thread)
private volatile int _sessionCount;
private volatile int _trainCount;
private volatile int _packetCount;
private volatile int _contractCount;
private long _tickMsBits;
private long _ticks;
public string GameVersion { get; } = System.Reflection.CustomAttributeExtensions.GetCustomAttribute<System.Reflection.AssemblyInformationalVersionAttribute>(typeof(GameHost).Assembly)?.InformationalVersion?.Split('+')[0] ?? "0.0.0";
public GameHost(ServerConfig config, GameData data, ILogger log, World? world = null)
{
_config = config;
_data = data;
_log = log;
_saves = new SaveStore(config.SavesDir, GameVersion);
_world = world ?? InitialWorld();
_lastTerrainHash = _world.Terrain.ComputeHash();
if (config.RecordPath is { Length: > 0 } path)
{
// registro dei comandi: si apre con un salvataggio di partenza accanto
_record = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read);
Protocol.CommandLogFile.WriteHeader(_record);
Core.Persistence.SaveFile.SaveToFile(_world, path + ".start.vfsave", GameVersion);
_world.CommandLog = [];
_log.LogInformation("Registro dei comandi in {Path}", path);
}
}
public SaveStore Saves => _saves;
public long NowMs => _clock.ElapsedMilliseconds;
public bool Healthy => _thread is { IsAlive: true } && NowMs - Interlocked.Read(ref _lastHeartbeatMs) < 5000;
public double TickMs => BitConverter.Int64BitsToDouble(Interlocked.Read(ref _tickMsBits));
public byte Speed => Volatile.Read(ref _speed);
private World InitialWorld()
{
string? latest = _saves.LatestAutosave();
if (latest is not null)
{
try
{
var w = _saves.Load(_data, latest);
_log.LogInformation("Partita ripresa dal salvataggio automatico {Save} ({Date})", latest, w.Clock.Date.ToString());
return w;
}
catch (Exception e)
{
_log.LogWarning(e, "Salvataggio automatico {Save} illeggibile: nuova partita", latest);
}
}
var settings = new NewGameSettings { Seed = _config.Seed, SizeKm = _config.MapSizeKm, DifficultyId = _config.Difficulty };
var world = WorldFactory.Create(_data, settings);
_log.LogInformation("Nuova partita: seme {Seed}, mappa {Size} km, difficoltà {Difficulty}", settings.Seed, settings.SizeKm, settings.DifficultyId);
return world;
}
public void Start()
{
_lastAutosaveMs = NowMs;
Interlocked.Exchange(ref _lastHeartbeatMs, NowMs);
_thread = new Thread(Run) { IsBackground = true, Name = "GameLoop" };
_thread.Start();
}
public void Dispose()
{
_stop = true;
_thread?.Join(5000);
_record?.Dispose();
}
/// <summary>Esegue un'azione sul thread del ciclo di gioco.</summary>
public void Post(Action action) => _inbox.Enqueue(action);
/// <summary>Esegue una funzione sul thread del ciclo di gioco e ne attende il risultato.</summary>
public Task<T> InvokeAsync<T>(Func<World, T> f)
{
var tcs = new TaskCompletionSource<T>(TaskCreationOptions.RunContinuationsAsynchronously);
Post(() =>
{
try
{
tcs.SetResult(f(_world));
}
catch (Exception e)
{
tcs.SetException(e);
}
});
return tcs.Task;
}
// ------------------------------------------------------------------ sessioni
/// <summary>Valida l'Hello e apre (o riprende) una sessione; il Welcome è il primo messaggio in coda.</summary>
public Task<(Session? Session, Reject? Reject)> OpenSessionAsync(Hello hello) => InvokeAsync<(Session?, Reject?)>(w =>
{
if (hello.ProtocolVersion != Frame.ProtocolVersion)
return (null, new Reject { Code = RejectCode.ProtocolVersion, Reason = $"Versione del protocollo {hello.ProtocolVersion}, il server usa la {Frame.ProtocolVersion}" });
if (_config.Token.Length > 0 && !FixedTimeEquals(hello.Token, _config.Token))
return (null, new Reject { Code = RejectCode.BadToken, Reason = "Token errato" });
if (hello.DataHash != 0 && hello.DataHash != _data.Hash)
return (null, new Reject { Code = RejectCode.DataMismatch, Reason = $"Dati di gioco diversi da quelli del server ({_data.Hash:x16})" });
if (hello.ResumeSessionId != 0 && _sessions.TryGetValue(hello.ResumeSessionId, out var old) && !old.Connected)
{
old.Attach();
old.Send(Welcome(old));
_log.LogInformation("Sessione {Session} ripresa", old.Id);
UpdateSessionCount();
return (old, null);
}
if (_sessions.Values.Count(s => s.Connected) >= _config.MaxSessions)
return (null, new Reject { Code = RejectCode.ServerFull, Reason = "Server pieno" });
ulong id;
do id = BitConverter.ToUInt64(RandomNumberGenerator.GetBytes(8));
while (id == 0 || _sessions.ContainsKey(id));
// in F3 tutte le sessioni guidano la compagnia del giocatore (ADR 0009)
var session = new Session(id, w.Player.Id);
session.Attach();
_sessions[id] = session;
session.Send(Welcome(session));
_log.LogInformation("Sessione {Session} aperta (client {Client})", id, hello.ClientVersion);
UpdateSessionCount();
return (session, null);
});
public void Receive(Session session, IMessage message) => Post(() => Handle(session, message));
public void Detach(Session session) => Post(() =>
{
session.MarkDisconnected(NowMs);
_log.LogInformation("Sessione {Session} disconnessa", session.Id);
UpdateSessionCount();
});
private static bool FixedTimeEquals(string a, string b) =>
CryptographicOperations.FixedTimeEquals(Encoding.UTF8.GetBytes(a), Encoding.UTF8.GetBytes(b));
private void UpdateSessionCount() => _sessionCount = _sessions.Values.Count(s => s.Connected);
private Welcome Welcome(Session s) => new()
{
SessionId = s.Id,
Summary = Projection.Summary(_world, _world.Companies[s.Company.Value], _speed),
DataHash = _data.Hash,
Difficulty = _world.Difficulty.Id,
};
private void Handle(Session s, IMessage message)
{
if (!s.Connected) return;
switch (message)
{
case Ping m:
s.Send(new Pong { Nonce = m.Nonce, ServerTick = (ulong)_world.Clock.Tick });
break;
case Subscribe m:
s.Viewport = m;
SendChunks(s);
foreach (var key in s.MotionSent.Keys.ToList()) s.MotionSent[key] = (-1, 255);
break;
case CommandMessage m:
uint seq = ++_serverSeq;
_pending[seq] = (s, m.Seq);
_world.Enqueue(m.Command with { Issuer = s.Company, Seq = seq });
break;
case SetSpeed m:
_speed = Speeds.Contains(m.Speed) ? m.Speed : (byte)1;
_effectiveSpeed = Math.Max(1, (int)_speed);
_slow = false;
_log.LogInformation("Velocità {Speed}×", _speed);
break;
case RequestDetail m:
SendDetail(s, m);
break;
case ListSaves:
s.Send(new SaveList { Saves = _saves.List() });
break;
case Save m:
SaveNow(m.Name.Length > 0 ? m.Name : "partita");
s.Send(new SaveList { Saves = _saves.List() });
break;
case Load m:
try
{
ReplaceWorld(_saves.Load(_data, m.SaveId), $"caricato {m.SaveId}");
}
catch (Exception e)
{
_log.LogWarning(e, "Caricamento di {Save} fallito", m.SaveId);
s.Send(Notice($"Caricamento non riuscito: {e.Message}"));
}
break;
case NewGame m:
try
{
var preset = _data.DifficultyPreset(m.DifficultyPreset.Length > 0 ? m.DifficultyPreset : _config.Difficulty);
var settings = new NewGameSettings
{
Seed = m.Seed,
SizeKm = m.SizeKm > 0 ? m.SizeKm : _config.MapSizeKm,
StartYear = m.StartYear > 0 ? m.StartYear : null,
DifficultyId = preset.Id,
DifficultyOverride = m.Overrides.Count > 0 ? DifficultyOverrides.Apply(preset, m.Overrides) : null,
Endless = m.EndlessFlags == 0 ? EndlessFlags.Default : (EndlessFlags)m.EndlessFlags,
};
ReplaceWorld(WorldFactory.Create(_data, settings), $"nuova partita, seme {settings.Seed}");
}
catch (Exception e)
{
_log.LogWarning(e, "Nuova partita rifiutata");
s.Send(Notice($"Nuova partita non creata: {e.Message}"));
}
break;
}
}
private static Notification Notice(string text) => new()
{
Event = new EventInfo { Severity = (byte)EventSeverity.Warning, Text = text },
};
public Protocol.Messages.SaveInfo SaveNow(string name)
{
var info = _saves.Save(_world, name);
_log.LogInformation("Salvataggio {Save} ({Bytes} byte)", info.SaveId, info.SizeBytes);
return info;
}
private void ReplaceWorld(World world, string why)
{
_world = world;
_pending.Clear();
_dayEvents.Clear();
_lastTerrainHash = world.Terrain.ComputeHash();
foreach (var s in _sessions.Values)
{
s.ResetCaches();
if (s.Connected) s.Send(Welcome(s));
}
_log.LogInformation("Mondo sostituito: {Why}", why);
}
// ------------------------------------------------------------------ ciclo
private void Run()
{
double due = 0;
long last = Stopwatch.GetTimestamp();
while (!_stop)
{
long now = Stopwatch.GetTimestamp();
double elapsedMs = Stopwatch.GetElapsedTime(last, now).TotalMilliseconds;
last = now;
try
{
while (_inbox.TryDequeue(out var action)) action();
if (_speed > 0)
{
due += elapsedMs * _effectiveSpeed / _config.TickMs;
due = Math.Min(due, 4 * _effectiveSpeed);
}
else
{
due = 0;
}
long budgetEnd = Stopwatch.GetTimestamp() + (long)(Stopwatch.Frequency * _config.TickMs / 1000.0);
while (due >= 1 && !_stop)
{
RunTick();
due -= 1;
if (Stopwatch.GetTimestamp() > budgetEnd) break;
}
AdjustSpeed();
Publish();
Autosave();
}
catch (Exception e)
{
_log.LogError(e, "Errore nel ciclo di gioco");
}
Interlocked.Exchange(ref _lastHeartbeatMs, NowMs);
double untilNext = _speed == 0 ? 10 : (1 - due) * _config.TickMs / _effectiveSpeed;
if (untilNext >= 2) Thread.Sleep((int)Math.Min(untilNext - 1, 10));
else Thread.Yield();
}
}
private void RunTick()
{
var w = _world;
bool newDay = w.Clock.IsNewDay;
bool newMonth = w.Clock.IsNewMonth;
long start = Stopwatch.GetTimestamp();
w.Tick();
double ms = Stopwatch.GetElapsedTime(start).TotalMilliseconds;
_tickMsEma = _tickMsEma == 0 ? ms : _tickMsEma * 0.98 + ms * 0.02;
Interlocked.Exchange(ref _tickMsBits, BitConverter.DoubleToInt64Bits(_tickMsEma));
Interlocked.Increment(ref _ticks);
if (_record is not null && w.CommandLog is { Count: > 0 } log)
{
foreach (var (tick, command) in log) Protocol.CommandLogFile.Append(_record, tick, command);
log.Clear();
_record.Flush();
}
foreach (var r in w.DrainResults())
{
if (r.Ok) _publishDirty = true;
if (!_pending.Remove(r.Seq, out var p)) continue;
p.Session.Send(new CommandResultMessage
{
Seq = p.ClientSeq, Type = (ushort)r.Type, Error = (ushort)r.Error, Message = r.Message, Created = r.Created, Tick = r.Tick,
});
// le convenzioni cambiano il Registro degli impieghi: lo si rimanda subito
if (r.Ok && r.Type is CommandType.AcceptAgreement or CommandType.RejectAgreement)
p.Session.Send(Projection.Employment(w, p.Session.Company));
}
foreach (var a in w.Alerts)
{
var alert = new MaintenanceAlert
{
Train = a.Train.Value, Depot = a.Depot.Value, Component = a.Component, Condition = (float)a.Condition, DueDays = a.DueDays, Text = a.Text,
};
foreach (var s in _sessions.Values)
{
if (s.Connected && s.Company == a.Company) s.Send(alert);
}
}
w.Alerts.Clear();
foreach (var e in w.Events.Drain())
{
var info = Projection.Event(e);
_dayEvents.Add(info);
if (e.Severity == EventSeverity.Info) continue;
foreach (var s in _sessions.Values)
{
if (s.Connected && (!e.Company.IsValid || e.Company == s.Company)) s.Send(new Notification { Event = info });
}
}
if (newDay) _dailyDue = true;
if (newMonth) _monthlyDue = true;
}
/// <summary>Budget: se i tick costano più del tempo disponibile si dimezza la velocità effettiva.</summary>
private void AdjustSpeed()
{
if (_speed == 0 || _tickMsEma <= 0) return;
double budget = _config.TickMs;
bool wasSlow = _slow;
if (_tickMsEma * _effectiveSpeed > budget * 0.9 && _effectiveSpeed > 1)
{
_effectiveSpeed = Math.Max(1, _effectiveSpeed / 2);
}
else if (_effectiveSpeed < _speed && _tickMsEma * _effectiveSpeed * 2 < budget * 0.5)
{
_effectiveSpeed = Math.Min(_speed, _effectiveSpeed * 2);
}
_slow = _effectiveSpeed < _speed || _tickMsEma > budget;
if (_slow && !wasSlow) _log.LogWarning("Tick medio {TickMs:F2} ms: velocità effettiva ridotta a {Speed}× su {Requested}×", _tickMsEma, _effectiveSpeed, _speed);
else if (!_slow && wasSlow) _log.LogInformation("Velocità di nuovo a {Speed}×", _speed);
}
private void Autosave()
{
if (_config.AutosaveMinutes <= 0 || NowMs - _lastAutosaveMs < _config.AutosaveMinutes * 60_000L) return;
_lastAutosaveMs = NowMs;
try
{
var info = _saves.Autosave(_world);
_log.LogInformation("Salvataggio automatico {Save}", info.SaveId);
}
catch (Exception e)
{
_log.LogError(e, "Salvataggio automatico fallito");
}
}
// ------------------------------------------------------------------ pubblicazione
private void Publish()
{
long now = NowMs;
foreach (var s in _sessions.Values)
{
if (s.Connected && s.NeedsFullState) SendFullState(s);
}
if (_dailyDue)
{
_dailyDue = false;
PublishDaily();
_publishDirty = true;
}
if (_publishDirty)
{
_publishDirty = false;
PublishDeltas();
}
if (now - _lastMotionMs >= MotionIntervalMs)
{
_lastMotionMs = now;
PublishMotion();
}
foreach (var s in _sessions.Values.Where(s => !s.Connected && now - s.DisconnectedAtMs > ResumeWindowMs).ToList())
{
_sessions.Remove(s.Id);
foreach (var key in _pending.Where(p => p.Value.Session == s).Select(p => p.Key).ToList()) _pending.Remove(key);
}
}
private void SendFullState(Session s)
{
s.ResetCaches();
s.NeedsFullState = false;
var entities = Projection.Entities(_world);
s.Send(new EntitySnapshot { Tick = _world.Clock.Tick, Entities = entities });
foreach (var (key, hash, _) in Records(entities)) s.EntityHashes[key] = hash;
var edges = new List<EdgeInfo>();
foreach (var e in _world.Network.Edges)
{
if (e.State == Core.Rail.EdgeState.Demolished) continue;
var info = Projection.Edge(_world, e);
edges.Add(info);
s.EdgeHashes[e.Id.Value] = Projection.Hash(info);
}
SendTrack(s, edges, []);
SendChunks(s);
}
/// <summary>TrackWorks in lotti sotto il megabyte (il frame massimo è 4 MB).</summary>
private static void SendTrack(Session s, List<EdgeInfo> edges, List<int> removed)
{
var batch = new TrackWorks { Removed = removed };
long bytes = 0;
foreach (var e in edges)
{
long size = 64 + e.S.Length * 49L + e.Signals.Length * 8L;
if (batch.Edges.Count > 0 && bytes + size > TrackBatchBytes)
{
s.Send(batch);
batch = new TrackWorks();
bytes = 0;
}
batch.Edges.Add(e);
bytes += size;
}
if (batch.Edges.Count > 0 || batch.Removed.Count > 0) s.Send(batch);
}
/// <summary>Chunk del viewport (con un chunk di margine) non ancora inviati.</summary>
private void SendChunks(Session s)
{
if (s.Viewport is not { } v) return;
var t = _world.Terrain;
int cs = t.ChunkCells;
int cx0 = Math.Max(0, Math.Min(v.X0, v.X1) / cs - 1), cy0 = Math.Max(0, Math.Min(v.Y0, v.Y1) / cs - 1);
int cx1 = Math.Min(t.ChunksX - 1, Math.Max(v.X0, v.X1) / cs + 1), cy1 = Math.Min(t.ChunksY - 1, Math.Max(v.Y0, v.Y1) / cs + 1);
for (int cy = cy0; cy <= cy1; cy++)
{
for (int cx = cx0; cx <= cx1; cx++)
{
if (!s.SentChunks.Add((cx, cy))) continue;
s.ChunkHashes[(cx, cy)] = Projection.ChunkHash(_world, cx, cy);
s.Send(Projection.Chunk(_world, cx, cy));
}
}
}
private static IEnumerable<((EntityType, int) Key, ulong Hash, IWritable Record)> Records(EntityLists e)
{
foreach (var x in e.Companies) yield return ((EntityType.Company, x.Id), Projection.Hash(x), x);
foreach (var x in e.Towns) yield return ((EntityType.Town, x.Id), Projection.Hash(x), x);
foreach (var x in e.Industries) yield return ((EntityType.Industry, x.Id), Projection.Hash(x), x);
foreach (var x in e.Hubs) yield return ((EntityType.Hub, x.Id), Projection.Hash(x), x);
foreach (var x in e.Nodes) yield return ((EntityType.Node, x.Id), Projection.Hash(x), x);
foreach (var x in e.Stations) yield return ((EntityType.Station, x.Id), Projection.Hash(x), x);
foreach (var x in e.Depots) yield return ((EntityType.Depot, x.Id), Projection.Hash(x), x);
foreach (var x in e.Lines) yield return ((EntityType.Line, x.Id), Projection.Hash(x), x);
foreach (var x in e.Vehicles) yield return ((EntityType.Vehicle, x.Id), Projection.Hash(x), x);
foreach (var x in e.Trains) yield return ((EntityType.Train, x.Id), Projection.Hash(x), x);
}
private void PublishDeltas()
{
var connected = _sessions.Values.Where(s => s.Connected && !s.NeedsFullState).ToList();
if (connected.Count == 0) return;
var records = Records(Projection.Entities(_world)).ToList();
var present = records.Select(r => r.Key).ToHashSet();
var edges = new List<(int Id, ulong Hash, EdgeInfo Info)>();
foreach (var e in _world.Network.Edges)
{
if (e.State == Core.Rail.EdgeState.Demolished) continue;
var info = Projection.Edge(_world, e);
edges.Add((e.Id.Value, Projection.Hash(info), info));
}
var liveEdges = edges.Select(e => e.Id).ToHashSet();
foreach (var s in connected)
{
var changed = new EntityLists();
foreach (var (key, hash, record) in records)
{
if (s.EntityHashes.TryGetValue(key, out ulong old) && old == hash) continue;
s.EntityHashes[key] = hash;
Add(changed, record);
}
var removed = s.EntityHashes.Keys.Where(k => !present.Contains(k)).OrderBy(k => k.Type).ThenBy(k => k.Id).ToList();
foreach (var k in removed) s.EntityHashes.Remove(k);
if (changed.TotalCount > 0 || removed.Count > 0)
s.Send(new EntityDelta { Tick = _world.Clock.Tick, Changed = changed, Removed = removed });
var changedEdges = new List<EdgeInfo>();
foreach (var (id, hash, info) in edges)
{
if (s.EdgeHashes.TryGetValue(id, out ulong old) && old == hash) continue;
s.EdgeHashes[id] = hash;
changedEdges.Add(info);
}
var removedEdges = s.EdgeHashes.Keys.Where(id => !liveEdges.Contains(id)).OrderBy(id => id).ToList();
foreach (int id in removedEdges) s.EdgeHashes.Remove(id);
if (changedEdges.Count > 0 || removedEdges.Count > 0) SendTrack(s, changedEdges, removedEdges);
}
}
private static void Add(EntityLists lists, IWritable record)
{
switch (record)
{
case CompanyInfo x: lists.Companies.Add(x); break;
case TownInfo x: lists.Towns.Add(x); break;
case IndustryInfo x: lists.Industries.Add(x); break;
case HubInfo x: lists.Hubs.Add(x); break;
case NodeInfo x: lists.Nodes.Add(x); break;
case StationInfo x: lists.Stations.Add(x); break;
case DepotInfo x: lists.Depots.Add(x); break;
case LineInfo x: lists.Lines.Add(x); break;
case VehicleInfo x: lists.Vehicles.Add(x); break;
case TrainInfo x: lists.Trains.Add(x); break;
}
}
private void PublishDaily()
{
var w = _world;
_trainCount = w.Trains.Count(t => !t.Removed);
_packetCount = w.Network.Stations.Sum(s => s.Waiting.Count) + w.Trains.Sum(t => t.Cargo.Count);
_contractCount = w.Commutes.Count;
// il terreno cambia quando le città si allargano o le industrie nascono e chiudono
ulong terrain = w.Terrain.ComputeHash();
bool terrainChanged = terrain != _lastTerrainHash;
_lastTerrainHash = terrain;
foreach (var s in _sessions.Values)
{
if (!s.Connected || s.NeedsFullState) continue;
var company = w.Companies[s.Company.Value];
var events = _dayEvents.Where(e => e.Company < 0 || e.Company == s.Company.Value).ToList();
s.Send(Projection.Digest(w, company, events, _slow, _speed, (float)_tickMsEma));
if (terrainChanged)
{
foreach (var key in s.SentChunks.OrderBy(k => k.Cy).ThenBy(k => k.Cx))
{
ulong h = Projection.ChunkHash(w, key.Cx, key.Cy);
if (s.ChunkHashes.TryGetValue(key, out ulong old) && old == h) continue;
s.ChunkHashes[key] = h;
s.Send(Projection.Chunk(w, key.Cx, key.Cy));
}
}
if (_monthlyDue) s.Send(Projection.Employment(w, s.Company));
// listino di borsa del giorno (12.2) e, a fine partita, la Cronaca finale una volta per sessione
s.Send(Projection.Tape(w, s.Company));
if (w.GameOver is not null && !s.ChronicleSent)
{
s.Send(Projection.Chronicle(w));
s.ChronicleSent = true;
}
}
_monthlyDue = false;
_dayEvents.Clear();
}
/// <summary>Dettagli su richiesta: cartella di manutenzione, registro officina, registro degli impieghi.</summary>
private void SendDetail(Session s, RequestDetail m)
{
var w = _world;
switch (m.Kind)
{
case DetailKind.TrainCard:
if (m.Target >= 0 && m.Target < w.Trains.Count && w.Trains[m.Target] is { Removed: false } t && t.Owner == s.Company)
s.Send(Projection.Card(w, t));
break;
case DetailKind.Workshop:
if (m.Target >= 0 && m.Target < w.Network.Depots.Count && w.Network.Depots[m.Target] is { } d && d.Owner == s.Company && w.Network.IsAlive(d))
s.Send(Projection.Workshop(w, d));
break;
case DetailKind.Employment:
s.Send(Projection.Employment(w, s.Company));
break;
case DetailKind.Company:
if (m.Target >= 0 && m.Target < w.Companies.Count) s.Send(Projection.CompanyCard(w, w.Companies[m.Target]));
break;
case DetailKind.Industry:
if (m.Target >= 0 && m.Target < w.Industries.Count && !w.Industries[m.Target].Closed)
s.Send(Projection.IndustryCard(w, w.Industries[m.Target]));
break;
case DetailKind.Chronicle:
s.Send(Projection.Chronicle(w));
break;
}
}
private void PublishMotion()
{
var w = _world;
var sessions = _sessions.Values.Where(s => s.Connected && !s.NeedsFullState && s.Viewport is not null).ToList();
if (sessions.Count == 0) return;
double cell = w.Terrain.CellSizeM, margin = w.Terrain.ChunkCells * cell;
var motions = new List<(TrainMotion Motion, Vec2 Head)>();
foreach (var t in w.Trains)
{
var m = Projection.Motion(w, t);
var head = Projection.HeadPoint(w, t);
if (m is not null && head is { } h) motions.Add((m, h));
}
foreach (var s in sessions)
{
var v = s.Viewport!;
double x0 = Math.Min(v.X0, v.X1) * cell - margin, x1 = (Math.Max(v.X0, v.X1) + 1) * cell + margin;
double y0 = Math.Min(v.Y0, v.Y1) * cell - margin, y1 = (Math.Max(v.Y0, v.Y1) + 1) * cell + margin;
foreach (var (m, head) in motions)
{
if (head.X < x0 || head.X > x1 || head.Y < y0 || head.Y > y1) continue;
bool moving = m.Speed > 0;
if (!moving && s.MotionSent.TryGetValue(m.TrainId, out var last) && last.State == m.State && last.Tick >= 0) continue;
if (s.SendDroppable(m)) s.MotionSent[m.TrainId] = (m.Tick, m.State);
}
}
}
// ------------------------------------------------------------------ metriche
/// <summary>Metriche in formato Prometheus (testo).</summary>
public string Metrics()
{
var sb = new StringBuilder();
void Gauge(string name, string help, double value)
{
sb.Append("# HELP ").Append(name).Append(' ').Append(help).Append('\n');
sb.Append("# TYPE ").Append(name).Append(" gauge\n");
sb.Append(name).Append(' ').Append(value.ToString("0.######", CultureInfo.InvariantCulture)).Append('\n');
}
Gauge("tick_ms", "Durata media di un tick in millisecondi", TickMs);
Gauge("trains", "Treni in servizio", _trainCount);
Gauge("packets", "Pacchetti di merci e passeggeri", _packetCount);
Gauge("contracts", "Contratti di pendolarismo", _contractCount);
Gauge("sessions", "Sessioni collegate", _sessionCount);
Gauge("ticks_total", "Tick eseguiti dall'avvio", Interlocked.Read(ref _ticks));
Gauge("speed", "Velocità richiesta", _speed);
return sb.ToString();
}
}
+115
View File
@@ -0,0 +1,115 @@
using System.Net.Http;
using System.Text.Json.Serialization;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Hosting.Server.Features;
using RailEnterprise.Core.Data;
using RailEnterprise.Core.Simulation;
using ProtocolSaveInfo = RailEnterprise.Protocol.Messages.SaveInfo;
namespace RailEnterprise.Server;
/// <summary>
/// Server autorevole di Rail Enterprise: 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("RailEnterprise.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;
+521
View File
@@ -0,0 +1,521 @@
using RailEnterprise.Core.Common;
using RailEnterprise.Core.Economy;
using RailEnterprise.Core.Rail;
using RailEnterprise.Core.Data;
using RailEnterprise.Core.Simulation;
using RailEnterprise.Core.Simulation.Systems;
using RailEnterprise.Protocol;
using RailEnterprise.Protocol.Messages;
namespace RailEnterprise.Server;
/// <summary>
/// Proiezione del mondo autorevole nei record del protocollo. Gira sul thread del ciclo di gioco:
/// legge il mondo, non lo modifica.
/// </summary>
public static class Projection
{
public static WorldSummary Summary(World w, Company company, byte speed) => new()
{
Seed = w.Settings.Seed,
SizeKm = w.Settings.SizeKm,
StartYear = w.Settings.StartYear,
Tick = w.Clock.Tick,
Date = w.Clock.Date.ToString(),
CompanyId = company.Id.Value,
CompanyName = company.Name,
RegionId = w.Settings.RegionId,
WidthCells = w.Terrain.Width,
HeightCells = w.Terrain.Height,
CellSizeM = w.Terrain.CellSizeM,
ChunkCells = w.Terrain.ChunkCells,
Speed = speed,
TerrainHash = w.Terrain.ComputeHash(),
CostMultiplier = RailCommandHandlers.CostMultiplier(w, company),
};
public static MapChunk Chunk(World w, int cx, int cy)
{
var t = w.Terrain;
int x0 = cx * t.ChunkCells, y0 = cy * t.ChunkCells;
int width = Math.Min(t.ChunkCells, t.Width - x0), height = Math.Min(t.ChunkCells, t.Height - y0);
var heights = new ushort[width * height];
var types = new byte[width * height];
var river = new byte[width * height];
for (int y = 0; y < height; y++)
{
int src = (y0 + y) * t.Width + x0;
t.Heights.AsSpan(src, width).CopyTo(heights.AsSpan(y * width));
t.Types.AsSpan(src, width).CopyTo(types.AsSpan(y * width));
t.RiverWidth.AsSpan(src, width).CopyTo(river.AsSpan(y * width));
}
return new MapChunk { Cx = cx, Cy = cy, Width = width, Height = height, Heights = heights, Types = types, RiverWidth = river };
}
/// <summary>Hash del contenuto di un chunk (per rimandarlo quando l'abitato o un'industria cambia il terreno).</summary>
public static ulong ChunkHash(World w, int cx, int cy)
{
var t = w.Terrain;
int x0 = cx * t.ChunkCells, y0 = cy * t.ChunkCells;
int width = Math.Min(t.ChunkCells, t.Width - x0), height = Math.Min(t.ChunkCells, t.Height - y0);
ulong h = 0;
for (int y = 0; y < height; y++)
{
int src = (y0 + y) * t.Width + x0;
h = XxHash64.Hash(t.Types.AsSpan(src, width), h);
h = XxHash64.Hash(System.Runtime.InteropServices.MemoryMarshal.AsBytes(t.Heights.AsSpan(src, width)), h);
}
return h;
}
/// <summary>Tutte le entità visibili a una compagnia (in F3: tutte).</summary>
public static EntityLists Entities(World w)
{
var net = w.Network;
var e = new EntityLists();
foreach (var c in w.Companies)
{
e.Companies.Add(new CompanyInfo
{
Id = c.Id.Value, Name = c.Name, Color = c.Color, IsPlayer = c.IsPlayer, Cash = c.Cash, NetWorth = c.NetWorth,
Rating = c.Rating.ToString(), Tier = (byte)c.Tier, Bankrupt = c.Bankrupt, MaintenancePolicy = (byte)c.MaintenancePolicy,
Personality = c.AiPersonality ?? "", Listed = c.Listed, SharePriceCents = Math.Round(c.SharePrice, 2), Sentiment = (float)c.Sentiment,
FounderShare = (float)c.Shares.FounderFraction, ControlledBy = c.ControlledBy.Value, Merged = c.Merged,
Receivership = c.Receivership, ReceivershipUntilDay = c.ReceivershipUntilDay, AnnualProfit = new Money(c.AnnualProfit),
});
}
foreach (var t in w.Towns)
{
e.Towns.Add(new TownInfo
{
Id = t.Id.Value, Name = t.Name, Position = t.Position, Population = t.Population, RadiusCells = t.RadiusCells,
Satisfaction = (float)t.OverallSatisfaction, Services = t.Services,
});
}
foreach (var i in w.Industries)
{
e.Industries.Add(new IndustryInfo
{
Id = i.Id.Value, Type = i.Def.Id, Name = i.Name, Position = i.Position, FootprintCells = i.FootprintCells, Level = i.Level,
Closed = i.Closed, Efficiency = (float)i.Efficiency, Condition = (float)Math.Round(i.Condition, 1), Owner = i.Owner.IsValid ? i.Owner.Value : -1,
Budget = (byte)i.Budget, SpareParts = i.SpareParts, Machinery = i.Machinery, StoppedUntilDay = i.StoppedUntilDay,
StopKind = (byte)i.StopKind, PendingWork = (byte)i.PendingWork, PartsShort = i.PartsShort,
});
}
foreach (var h in w.Hubs)
e.Hubs.Add(new HubInfo { Id = h.Id.Value, Kind = h.Kind.ToString().ToLowerInvariant(), Name = h.Name, Position = h.Position });
foreach (var n in net.Nodes)
{
if (n.Removed) continue;
e.Nodes.Add(new NodeInfo
{
Id = n.Id.Value, Position = n.Position, HeightM = n.HeightM, Owner = n.Owner.Value, Station = n.Station.Value, Depot = n.Depot.Value,
Edges = n.Edges.Select(x => x.Value).ToArray(),
});
}
foreach (var s in net.Stations)
{
if (!net.IsAlive(s)) continue;
int waiting = 0;
foreach (var p in s.Waiting) waiting += p.Units;
e.Stations.Add(new StationInfo
{
Id = s.Id.Value, Owner = s.Owner.Value, Name = s.Name, Node = s.Node.Value, Position = s.Position, Platforms = s.Platforms,
WaitingUnits = waiting, Industries = s.Industries.Select(x => x.Value).ToArray(), Towns = s.Towns.Select(x => x.Value).ToArray(),
});
}
foreach (var d in net.Depots)
{
if (!net.IsAlive(d)) continue;
bool waiting = false;
foreach (var j in d.Jobs) waiting |= j.InStall && !j.Started && d.SpareParts < j.Parts;
e.Depots.Add(new DepotInfo
{
Id = d.Id.Value, Owner = d.Owner.Value, Name = d.Name, Node = d.Node.Value, Position = d.Position, Size = d.Size,
Stalls = d.Stalls, JobsStaff = d.JobsStaff, StaffPercent = (byte)Math.Round(d.StaffRatio * 100), SpareParts = d.SpareParts,
PartsTarget = d.PartsTarget, Jobs = d.Jobs.Count, WaitingParts = waiting,
});
}
foreach (var l in w.Lines)
{
if (l.Removed) continue;
e.Lines.Add(new LineInfo
{
Id = l.Id.Value, Owner = l.Owner.Value, Name = l.Name, Color = l.Color, Stops = l.Stops.ToArray(),
Policy = l.Policy is { } p ? (byte)p : byte.MaxValue,
});
}
foreach (var v in w.Vehicles)
{
if (v.Sold) continue;
// condizione arrotondata all'unità: il record cambia (e viaggia nei delta) solo quando serve
double cond = Math.Floor(v.Components.Length == 0 ? 100 : v.Components.Min());
e.Vehicles.Add(new VehicleInfo { Id = v.Id.Value, Owner = v.Owner.Value, Type = v.Def.Id, Depot = v.Depot.Value, Train = v.Train.Value, Condition = (float)cond });
}
foreach (var t in w.Trains)
{
if (t.Removed) continue;
int load = 0, capacity = 0;
foreach (var vid in t.Vehicles)
{
var v = w.Vehicles[vid.Value];
load += v.Load + v.Pax;
capacity += (v.Def.Capacity ?? 0) + (v.Def.PaxCapacity ?? 0);
}
var atDepot = t.AtNode.IsValid ? net.Nodes[t.AtNode.Value].Depot : DepotId.None;
var next = t.Vehicles.Count > 0 ? Fleet.Next(w, t) : new NextIntervention(-1, 0);
e.Trains.Add(new TrainInfo
{
Id = t.Id.Value, Owner = t.Owner.Value, Name = t.Name, Line = t.Line.Value, State = (byte)t.State,
Vehicles = t.Vehicles.Select(x => x.Value).ToArray(), MaxSpeedKmh = (float)t.MaxSpeedKmh, LengthM = (float)t.LengthM,
Load = load, Capacity = capacity, Depot = atDepot.Value,
Condition = (byte)Math.Clamp(Math.Floor(Fleet.TrainCondition(w, t)), 0, 100), Maintenance = MaintenanceStatus(t),
Reserve = t.Reserve, Policy = t.Policy is { } p ? (byte)p : byte.MaxValue,
NextIntervention = next.Intervention >= 0 ? w.Data.Maintenance.Interventions[next.Intervention].Id : "",
NextDueDays = (int)Math.Clamp(Math.Floor(next.Days), -9999, 9999), MaintenanceDepot = t.MaintenanceDepot.Value,
});
}
return e;
}
public static TrainMaintenanceStatus MaintenanceStatus(Train t)
{
if (t.State == TrainState.Broken) return TrainMaintenanceStatus.Stranded;
if (t.Towed) return TrainMaintenanceStatus.Towed;
if (t.InWorkshop) return TrainMaintenanceStatus.InWorkshop;
if (t.Failure == FailureKind.Minor) return TrainMaintenanceStatus.MinorFailure;
return t.MaintenanceDepot.IsValid ? TrainMaintenanceStatus.Booked : TrainMaintenanceStatus.InService;
}
/// <summary>Cartella di manutenzione di un treno (10.3).</summary>
public static MaintenanceCard Card(World w, Train t)
{
var m = w.Data.Maintenance;
var next = t.Vehicles.Count > 0 ? Fleet.Next(w, t) : new NextIntervention(-1, 0);
var card = new MaintenanceCard
{
Train = t.Id.Value, Day = w.Clock.Day, Condition = (float)Fleet.TrainCondition(w, t), Status = MaintenanceStatus(t),
Policy = (byte)Fleet.PolicyOf(w, t).Id, PolicyOverride = t.Policy is { } p ? (byte)p : byte.MaxValue, Reserve = t.Reserve,
Failure = (byte)t.Failure, FailedVehicle = t.FailedVehicle.Value,
FailedComponent = t.FailedVehicle.IsValid && t.FailedComponent >= 0
? Fleet.ComponentsOf(w.Data, w.Vehicles[t.FailedVehicle.Value].Def)[t.FailedComponent].Id : "",
RescueHours = t.RescueTick >= 0 ? (float)((t.RescueTick - w.Clock.Tick) * w.Calendar.TrainSecondsPerTick / 3600) : -1,
NextIntervention = next.Intervention >= 0 ? m.Interventions[next.Intervention].Id : "", NextDueDays = (float)next.Days,
PlannedIntervention = t.PlannedIntervention >= 0 ? m.Interventions[t.PlannedIntervention].Id : "",
MaintenanceDepot = t.MaintenanceDepot.Value, ServiceKmPerDay = (float)t.ServiceKmPerDay,
CostThisYear = new Money(t.MaintenanceThisYear), CostLastYear = new Money(t.MaintenanceLastYear),
FailuresThisYear = t.FailuresThisYear, FailuresTotal = t.FailuresTotal, CoveredBy = t.CoveredBy.Value, Covering = t.Covering.Value,
};
foreach (var id in t.Vehicles)
{
var v = w.Vehicles[id.Value];
var comps = Fleet.ComponentsOf(w.Data, v.Def);
var vc = new VehicleCard
{
Vehicle = v.Id.Value, Type = v.Def.Id, OdometerKm = (float)v.OdometerKm,
AgeYears = (float)((w.Clock.Day - v.BoughtDay) / (double)w.Calendar.DaysPerYear), AgeFactor = (float)Fleet.AgeFactor(w, v),
};
for (int j = 0; j < v.Components.Length && j < comps.Count; j++)
vc.Components.Add(new ComponentCard { Component = comps[j].Id, Condition = (float)v.Components[j], WearPerDay = j < v.WearEma.Length ? (float)v.WearEma[j] : 0 });
card.Vehicles.Add(vc);
}
foreach (var h in t.History)
{
card.History.Add(new MaintenanceRecordInfo
{
Day = h.Day, Intervention = m.Interventions[h.Intervention].Id, Cost = new Money(h.CostCents), Depot = h.Depot.Value, Parts = h.Parts,
});
}
return card;
}
/// <summary>Registro officina di un deposito (10.3).</summary>
public static WorkshopRegister Workshop(World w, Depot d)
{
var m = w.Data.Maintenance;
var backlog = new double[w.Network.Depots.Count];
var reserved = new int[w.Network.Depots.Count];
FleetMaintenanceSystem.DepotLoads(w, null, backlog, reserved);
var reg = new WorkshopRegister
{
Depot = d.Id.Value, Day = w.Clock.Day, Stalls = d.Stalls, JobsStaff = d.JobsStaff, StaffPresent = (float)d.StaffPresent,
WorkRate = (float)FleetMaintenanceSystem.WorkRate(w, d), SpareParts = d.SpareParts, PartsTarget = d.PartsTarget,
PartsReserved = reserved[d.Id.Value],
};
foreach (var j in d.Jobs)
{
reg.Jobs.Add(new WorkshopJobInfo
{
Train = j.Train.Value, Intervention = m.Interventions[j.Intervention].Id, InStall = j.InStall, Started = j.Started,
Progress = (float)j.Progress, Days = (float)j.Days, Parts = j.Parts, QueuedDay = j.QueuedDay,
});
}
foreach (var t in w.Trains)
{
if (t.Removed || t.InWorkshop || t.MaintenanceDepot != d.Id || t.PlannedIntervention < 0) continue;
var def = m.Interventions[t.PlannedIntervention];
reg.Booked.Add(new WorkshopJobInfo { Train = t.Id.Value, Intervention = def.Id, Days = def.Days, Parts = Fleet.PartsFor(w, t, def), QueuedDay = -1 });
}
return reg;
}
/// <summary>Testo italiano del motivo dei posti scoperti (per i lettori senza il blocco F4).</summary>
public static string ReasonText(World w, UncoveredReason reason, LineId line, PaxClass cls) => reason switch
{
UncoveredReason.NoStation => "nessuna stazione serve il posto di lavoro",
UncoveredReason.NoTownInReach => $"nessuna città raggiungibile entro {(cls == PaxClass.Staff ? w.Data.Balance.Employment.StaffMaxMinutes : w.Data.Balance.Employment.WorkerMaxMinutes):F0} min",
UncoveredReason.NoFreeWorkers => "le città raggiungibili non hanno lavoratori liberi",
UncoveredReason.NoStaffServices => "città senza servizi per il personale",
UncoveredReason.LineCapacity => $"capacità delle carrozze insufficiente sulla {(line.IsValid && line.Value < w.Lines.Count ? w.Lines[line.Value].Name : "linea")}",
_ => "",
};
/// <summary>
/// Registro degli impieghi della compagnia: industrie servite dai suoi treni e suoi depositi, con
/// provenienze, posti scoperti e motivi, più le convenzioni proposte o attive.
/// </summary>
public static EmploymentReport Employment(World w, CompanyId company)
{
var report = new EmploymentReport { Day = w.Clock.Day };
var places = new List<IWorkplace>();
EmploymentSystem.Workplaces(w, places);
foreach (var p in places)
{
bool mine = p is Depot depot && depot.Owner == company;
var sources = new List<EmploymentSource>();
foreach (var c in w.Commutes)
{
if (c.Workplace != p.Ref || (!mine && c.Carrier != company)) continue;
sources.Add(new EmploymentSource
{
Town = c.Town.Value, HomeStation = c.HomeStation.Value, Line = c.Route.Count > 0 ? c.Route[0].Value : -1,
Category = (byte)c.Category, Headcount = c.Headcount, Coverage = (float)c.Coverage,
});
}
bool served = w.Network.Stations.Any(s => s.Owner == company && w.Network.IsAlive(s) && p is Industry ind && s.Industries.Contains(ind.Id));
if (!mine && sources.Count == 0 && !served) continue;
string reason = string.Join("; ", new[]
{
ReasonText(w, p.WorkersReason, p.WorkersReasonLine, PaxClass.Worker),
ReasonText(w, p.StaffReason, p.StaffReasonLine, PaxClass.Staff),
}.Where(x => x.Length > 0));
report.Rows.Add(new EmploymentRow
{
Industry = p.Ref.Index, JobsWorkers = p.JobsWorkers, JobsStaff = p.JobsStaff,
WorkersPresent = (float)p.WorkersPresent, StaffPresent = (float)p.StaffPresent, Reason = reason, Sources = sources,
Kind = (byte)p.Ref.Kind, WorkersReason = (byte)p.WorkersReason, StaffReason = (byte)p.StaffReason,
WorkersReasonLine = p.WorkersReasonLine.Value, StaffReasonLine = p.StaffReasonLine.Value,
});
}
foreach (var a in w.Agreements)
{
if (a.Carrier != company) continue;
report.Agreements.Add(new AgreementInfo
{
Id = a.Id.Value, Industry = a.Industry.Value, Carrier = a.Carrier.Value, SeatsPerDay = a.SeatsPerDay, MonthlyFee = a.MonthlyFee,
State = (byte)a.State, ProposedDay = a.ProposedDay, StartDay = a.StartDay, EndDay = a.EndDay, Coverage = (float)a.Coverage,
ShortDays = a.ShortDays,
});
}
return report;
}
public static EdgeInfo Edge(World w, TrackEdge e)
{
float progress = 1;
if (e.Project >= 0 && e.Project < w.Network.Projects.Count)
{
var p = w.Network.Projects[e.Project];
if (!p.Done) progress = (float)Math.Clamp(p.ProgressDays / Math.Max(1, p.TotalDays), 0, 1);
}
return new EdgeInfo
{
Id = e.Id.Value, Owner = e.Owner.Value, A = e.A.Value, B = e.B.Value, TrackClass = (byte)e.TrackClass, DoubleTrack = e.DoubleTrack,
Electrified = e.Electrified, State = (byte)e.State, Condition = (float)e.Condition, StructureCondition = (float)e.StructureCondition,
Progress = progress, S = e.S, X = e.X, Y = e.Y, H = e.H, Ground = e.Ground, Kinds = e.Kinds.Select(k => (byte)k).ToArray(),
SpeedLimitKmh = e.SpeedLimitKmh, Signals = e.Signals.ToArray(),
};
}
/// <summary>
/// Moto di un treno: i passi del percorso dalla coda (testa meno lunghezza) fino al tratto
/// prenotato, con la distanza della testa misurata dal primo passo incluso.
/// </summary>
public static TrainMotion? Motion(World w, Train t)
{
if (t.Removed || t.Route.Count == 0 || t.State == TrainState.InDepot) return null;
var net = w.Network;
int index = Math.Clamp(t.RouteIndex, 0, t.Route.Count - 1);
double headInStep = Math.Min(t.StepPos, net.Edges[t.Route[index].Edge.Value].Length);
// risale fino al passo che contiene la coda
int first = index;
double behind = t.LengthM - headInStep;
while (behind > 0 && first > 0)
{
first--;
behind -= net.Edges[t.Route[first].Edge.Value].Length;
}
int last = Math.Clamp(Math.Max(index, t.ReservedStep), index, t.Route.Count - 1);
var segments = new List<MotionSegment>(last - first + 1);
double head = 0;
for (int i = first; i <= last; i++)
{
var step = t.Route[i];
double len = net.Edges[step.Edge.Value].Length;
segments.Add(step.Forward ? new MotionSegment(step.Edge.Value, true, 0, len) : new MotionSegment(step.Edge.Value, false, len, 0));
if (i < index) head += len;
}
head += headInStep;
double cond = 100;
foreach (var vid in t.Vehicles)
{
var v = w.Vehicles[vid.Value];
foreach (double c in v.Components) cond = Math.Min(cond, c);
}
return new TrainMotion
{
TrainId = t.Id.Value, Tick = w.Clock.Tick, State = (byte)t.State, Condition = (float)cond, Speed = (float)t.Speed,
LengthM = (float)t.LengthM, HeadDistance = head, Segments = segments,
};
}
/// <summary>Punto della testa del treno sul server (riferimento dei test di coerenza).</summary>
public static Vec2? HeadPoint(World w, Train t)
{
if (t.Route.Count == 0) return t.AtNode.IsValid ? w.Network.Nodes[t.AtNode.Value].Position : null;
int index = Math.Clamp(t.RouteIndex, 0, t.Route.Count - 1);
var step = t.Route[index];
var edge = w.Network.Edges[step.Edge.Value];
double s = Math.Min(t.StepPos, edge.Length);
return edge.PointAt(step.Forward ? s : edge.Length - s);
}
public static EventInfo Event(GameEvent e) => new()
{
Day = e.Day, Kind = (byte)e.Kind, Severity = (byte)e.Severity, Text = e.Text, Entity = (byte)e.Entity, EntityIndex = e.EntityIndex,
Company = e.Company.IsValid ? e.Company.Value : -1,
};
public static DailyDigest Digest(World w, Company company, List<EventInfo> events, bool slow, byte speed, float tickMs) => new()
{
Day = w.Clock.Day,
Tick = w.Clock.Tick,
Date = w.Clock.Date.ToString(),
Cash = company.Cash,
NetWorth = company.NetWorth,
Rating = company.Rating.ToString(),
Prices = w.Market.GlobalPrice.Select(p => Money.FromCentsRounded(p)).ToList(),
Events = events,
StateHash = w.LastStateHash,
Slow = slow,
Speed = speed,
TickMs = tickMs,
};
/// <summary>Hash di un record serializzato (per i delta per sessione).</summary>
public static ulong Hash(IWritable record)
{
var w = new SpanWriter(128);
record.Write(ref w);
return XxHash64.Hash(w.Written);
}
// ------------------------------------------------------------------ F5: borsa, industrie, Cronaca
/// <summary>Listino del giorno: prezzi delle compagnie attive e offerte pubbliche in corso.</summary>
public static MarketTape Tape(World w, CompanyId viewer)
{
var tape = new MarketTape { Day = w.Clock.Day };
foreach (var c in w.Companies)
{
if (c.Defunct) continue;
double last = c.PriceHistory.Count > 0 ? c.PriceHistory[^1] : c.SharePrice;
tape.Shares.Add(new SharePrice
{
Company = c.Id.Value, Price = Money.FromCentsRounded(c.SharePrice), Change = last > 0 ? (float)(c.SharePrice / last - 1) : 0,
Listed = c.Listed, PriceCents = Math.Round(c.SharePrice, 4), Outstanding = c.Shares.Outstanding, FreeFloat = Corporate.FreeFloat(w, c),
FounderShare = (float)c.Shares.FounderFraction, ControlledBy = c.ControlledBy.Value,
});
}
foreach (var b in w.Bids)
{
if (b.State != BidState.Open) continue;
var target = w.Company(b.Target);
tape.Bids.Add(new BidInfo
{
Bid = b.Id.Value, Bidder = b.Bidder.Value, Target = b.Target.Value, PricePerShare = new Money(b.PricePerShare), TargetShare = b.TargetShare,
ExpiresDay = b.EndDay, State = (byte)b.State,
CommittedShare = target.Shares.Outstanding > 0 ? (double)StockMarketSystem.Committed(w, b) / target.Shares.Outstanding : 0,
Defenses = b.Defenses, Knight = b.Knight.Value, Accepted = b.Accepted.Contains(viewer),
});
}
return tape;
}
private static CompanyYearInfo YearInfo(CompanyYear y) => new()
{
Year = y.Year, NetWorth = new Money(y.NetWorthCents), Cash = new Money(y.CashCents), Revenue = new Money(y.RevenueCents),
Profit = new Money(y.ProfitCents), Tier = (byte)y.Tier, Trains = y.Trains, TrackKm = (float)y.TrackKm, SharePrice = new Money(y.SharePriceCents),
};
/// <summary>Scheda di una compagnia: libro dei soci, prezzi mensili, storico annuale, asta.</summary>
public static CompanyCard CompanyCard(World w, Company c)
{
var holdings = new List<HoldingInfo>
{
new() { Holder = HoldingInfo.Founder, Shares = c.Shares.Founder },
new() { Holder = HoldingInfo.Market, Shares = c.Shares.Public },
};
for (int i = 0; i < c.Shares.ByCompany.Length; i++)
{
if (c.Shares.ByCompany[i] > 0) holdings.Add(new HoldingInfo { Holder = i, Shares = c.Shares.ByCompany[i] });
}
long dividends = 0;
foreach (long d in c.DividendRing) dividends += d;
var auction = w.Auctions.FirstOrDefault(a => a.Seller == c.Id && !a.Closed);
return new CompanyCard
{
Company = c.Id.Value, TotalShares = c.Shares.Total, Treasury = c.Shares.Treasury, Holdings = holdings,
PriceHistory = [.. c.PriceHistory], History = c.History.Select(YearInfo).ToList(),
AnnualProfit = new Money(c.AnnualProfit), DividendsYear = new Money(dividends), Debt = c.Debt, MarketCap = Money.FromCentsRounded(c.MarketCap),
ControlDays = c.ControlledBy.IsValid ? w.Clock.Day - c.ControlSinceDay : -1,
AuctionMin = new Money(auction?.MinPriceCents ?? 0), AuctionBest = new Money(auction?.BestPriceCents ?? 0),
AuctionBestBidder = auction?.BestBidder.Value ?? -1, AuctionEndDay = auction?.EndDay ?? -1,
};
}
/// <summary>Scheda del proprietario di un'industria (sezione 11).</summary>
public static IndustryCard IndustryCard(World w, Industry ind)
{
var m = w.Data.Balance.IndustryMaintenance;
var budget = m.For(ind.Budget);
double wear = m.WearPerDay * Math.Max(0, ind.Efficiency) * ind.Def.WearIntensity * w.Difficulty.WearMultiplier;
double recovery = budget.RecoveryPerDay * (ind.PartsShort ? m.NoPartsRecoveryFactor : 1);
double hazard = ind.Condition >= m.BreakdownPivot ? 0 : m.BreakdownBase * DMath.Exp((m.BreakdownPivot - ind.Condition) / m.BreakdownScale);
double perYear = 1 - DMath.Pow(1 - Math.Min(1, hazard), w.Calendar.DaysPerYear);
return new IndustryCard
{
Industry = ind.Id.Value, Margin = (float)ind.Margin, ConditionMultiplier = (float)IndustryMath.ConditionMultiplier(ind.Condition, m),
WearPerDay = (float)wear, RecoveryPerDay = (float)recovery, MaintenanceCostPerDay = Money.FromCentsRounded(ind.RevenueEma * budget.CostShareOfRevenue),
MaintenanceSpentYear = new Money(ind.MaintenanceSpentYear), PartsTarget = IndustryMath.PartsTarget(ind, m), PartsPerMonth = IndustryMath.MonthlyPartsUse(ind, m),
PartsOrdered = ind.PartsOrdered, MachineryRequired = IndustryMath.MachineryRequired(ind, m), UpgradeCost = IndustryMaintenanceSystem.UpgradeCost(ind),
Valuation = IndustryMath.Valuation(w, ind), Cash = ind.Cash, BreakdownChancePerYear = (float)perYear,
Stops = ind.StopHistory.Select(h => new IndustryStopInfo { Day = h.Day, Days = h.Days, Kind = (byte)h.Kind }).ToList(),
};
}
/// <summary>Cronaca finale (o provvisoria, se la partita è in corso) della compagnia del giocatore.</summary>
public static Chronicle Chronicle(World w)
{
var report = ChronicleReport.Build(w);
return new Chronicle
{
GameOver = w.GameOver is not null, Reason = (byte)(w.GameOver?.Reason ?? GameOverReason.None), Text = w.GameOver?.Text ?? "",
Winner = w.GameOver?.Winner.Value ?? -1, Day = w.GameOver?.Day ?? w.Clock.Day, Company = w.Player.Name,
FoundedYear = w.Calendar.StartYear, Prestige = report.Prestige,
History = report.History.Select(YearInfo).ToList(),
Records = report.Records.Select(r => new RecordInfo { Title = r.Title, Value = r.Value, Year = r.Year }).ToList(),
Highlights = report.Highlights,
};
}
}
@@ -0,0 +1,19 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<!-- Server autorevole: ASP.NET Core usato solo come shared framework. -->
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<RootNamespace>RailEnterprise.Server</RootNamespace>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\RailEnterprise.Core\RailEnterprise.Core.csproj" />
<ProjectReference Include="..\RailEnterprise.Protocol\RailEnterprise.Protocol.csproj" />
</ItemGroup>
<!-- I file dati viaggiano accanto all'eseguibile. -->
<ItemGroup>
<Content Include="..\..\data\**\*.json" LinkBase="data" CopyToOutputDirectory="PreserveNewest" CopyToPublishDirectory="PreserveNewest" />
</ItemGroup>
</Project>
+95
View File
@@ -0,0 +1,95 @@
using System.Globalization;
using RailEnterprise.Core.Data;
using RailEnterprise.Core.Persistence;
using RailEnterprise.Core.Simulation;
using ProtocolSaveInfo = RailEnterprise.Protocol.Messages.SaveInfo;
namespace RailEnterprise.Server;
/// <summary>
/// Salvataggi in <c>$RE_DATA_DIR/saves</c>: file <c>.vfsave</c>; i salvataggi automatici ruotano
/// sugli ultimi cinque. L'id di un salvataggio è il nome del file senza estensione.
/// </summary>
public sealed class SaveStore(string directory, string gameVersion)
{
public const string Extension = ".vfsave";
public const string AutosavePrefix = "autosave-";
public const int AutosaveKeep = 5;
public string Directory { get; } = directory;
public string PathOf(string id) => System.IO.Path.Combine(Directory, SaveFile.SafeFileName(id) + Extension);
public bool Exists(string id) => File.Exists(PathOf(id));
public ProtocolSaveInfo Save(World w, string name)
{
System.IO.Directory.CreateDirectory(Directory);
string stamp = DateTime.UtcNow.ToString("yyyyMMdd-HHmmss", CultureInfo.InvariantCulture);
string id = $"{SaveFile.SafeFileName(name)}-{stamp}";
return Write(w, id);
}
/// <summary>Salvataggio automatico con rotazione.</summary>
public ProtocolSaveInfo Autosave(World w)
{
System.IO.Directory.CreateDirectory(Directory);
string stamp = DateTime.UtcNow.ToString("yyyyMMdd-HHmmss-fff", CultureInfo.InvariantCulture);
var info = Write(w, AutosavePrefix + stamp);
var old = List().Where(s => s.Autosave).OrderByDescending(s => s.SavedUnixMs).ThenByDescending(s => s.SaveId, StringComparer.Ordinal).Skip(AutosaveKeep);
foreach (var s in old) File.Delete(PathOf(s.SaveId));
return info;
}
private ProtocolSaveInfo Write(World w, string id)
{
string path = PathOf(id);
string temp = path + ".tmp";
SaveFile.SaveToFile(w, temp, gameVersion);
File.Move(temp, path, overwrite: true);
return Describe(path) ?? throw new IOException($"Salvataggio illeggibile: {path}");
}
public World Load(GameData data, string id) => SaveFile.LoadFromFile(data, PathOf(id));
public List<ProtocolSaveInfo> List()
{
if (!System.IO.Directory.Exists(Directory)) return [];
var list = new List<ProtocolSaveInfo>();
foreach (string path in System.IO.Directory.GetFiles(Directory, "*" + Extension))
{
var info = Describe(path);
if (info is not null) list.Add(info);
}
list.Sort((a, b) => b.SavedUnixMs != a.SavedUnixMs ? b.SavedUnixMs.CompareTo(a.SavedUnixMs) : string.CompareOrdinal(a.SaveId, b.SaveId));
return list;
}
/// <summary>Il salvataggio automatico più recente, se c'è (ripresa dopo un riavvio del container).</summary>
public string? LatestAutosave() => List().FirstOrDefault(s => s.Autosave)?.SaveId;
private static ProtocolSaveInfo? Describe(string path)
{
try
{
var file = new FileInfo(path);
byte[] head = new byte[Math.Min(file.Length, 4096)];
using (var f = File.OpenRead(path)) f.ReadExactly(head);
var info = SaveFile.ReadInfo(head);
string id = System.IO.Path.GetFileNameWithoutExtension(path);
return new ProtocolSaveInfo
{
SaveId = id,
Name = info.CompanyName,
GameDate = info.Date,
SizeBytes = file.Length,
SavedUnixMs = new DateTimeOffset(file.LastWriteTimeUtc).ToUnixTimeMilliseconds(),
Autosave = id.StartsWith(AutosavePrefix, StringComparison.Ordinal),
};
}
catch (Exception)
{
return null;
}
}
}
+60
View File
@@ -0,0 +1,60 @@
using System.Collections;
namespace RailEnterprise.Server;
/// <summary>
/// Configurazione del server dalle variabili d'ambiente (sezione 14.2) e dagli argomenti
/// <c>--local</c>, <c>--healthcheck</c>, <c>--token</c>, <c>--port</c>, <c>--data</c>.
/// </summary>
public sealed class ServerConfig
{
public int Port { get; init; } = 7400;
public string Token { get; init; } = "";
public string DataDir { get; init; } = "/data";
public int TickMs { get; init; } = 50;
public int AutosaveMinutes { get; init; } = 10;
public ulong Seed { get; init; } = 1;
public int MapSizeKm { get; init; } = 128;
public string Difficulty { get; init; } = "imprenditore";
public string LogLevel { get; init; } = "Information";
/// <summary>Processo locale figlio del client: porta casuale su 127.0.0.1, stampa «LISTENING porta».</summary>
public bool Local { get; init; }
public bool HealthCheck { get; init; }
/// <summary>File in cui registrare i comandi eseguiti (per <c>railenterprise-tools replay</c>).</summary>
public string? RecordPath { get; init; }
/// <summary>Numero massimo di sessioni contemporanee.</summary>
public int MaxSessions { get; init; } = 16;
public string SavesDir => Path.Combine(DataDir, "saves");
public static ServerConfig From(string[] args, IDictionary environment)
{
string? Env(string name) => environment[name] as string is { Length: > 0 } v ? v : null;
string? Arg(string name)
{
for (int i = 0; i < args.Length - 1; i++)
{
if (args[i] == name) return args[i + 1];
}
return null;
}
bool local = args.Contains("--local");
string dataDir = Arg("--data") ?? Env("RE_DATA_DIR")
?? (local ? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "RailEnterprise") : "/data");
return new ServerConfig
{
Local = local,
HealthCheck = args.Contains("--healthcheck"),
RecordPath = Arg("--record") ?? Env("RE_RECORD"),
Port = int.TryParse(Arg("--port") ?? Env("RE_PORT"), out int port) ? port : 7400,
Token = Arg("--token") ?? Env("RE_TOKEN") ?? "",
DataDir = dataDir,
TickMs = int.TryParse(Env("RE_TICK_MS"), out int tick) && tick > 0 ? tick : 50,
AutosaveMinutes = int.TryParse(Env("RE_AUTOSAVE_MIN"), out int auto) ? auto : 10,
Seed = ulong.TryParse(Env("RE_SEED"), out ulong seed) ? seed : 1,
MapSizeKm = int.TryParse(Env("RE_MAP_SIZE"), out int size) ? size : 128,
Difficulty = Env("RE_DIFFICULTY") ?? "imprenditore",
LogLevel = Env("RE_LOG_LEVEL") ?? "Information",
};
}
}
+117
View File
@@ -0,0 +1,117 @@
using System.Net.WebSockets;
using System.Threading.Channels;
using RailEnterprise.Core.Common;
using RailEnterprise.Protocol;
using RailEnterprise.Protocol.Messages;
namespace RailEnterprise.Server;
/// <summary>
/// Sessione di un client. La coda d'invio ha due classi: i messaggi affidabili (chunk, entità,
/// esiti, resoconti) non si scartano mai; i moti dei treni si scartano quando la coda supera la
/// soglia (backpressure). Se gli affidabili superano il limite la sessione si chiude: il client
/// può riprenderla con il proprio sessionId.
/// </summary>
public sealed class Session
{
public const long DroppableLimitBytes = 256 * 1024;
public const long ReliableLimitBytes = 64L * 1024 * 1024;
public ulong Id { get; }
public CompanyId Company { get; }
private Channel<byte[]> _queue = Channel.CreateUnbounded<byte[]>(new UnboundedChannelOptions { SingleReader = true });
private long _pendingBytes;
public bool Connected { get; private set; }
public long DisconnectedAtMs { get; private set; }
public long DroppedMotions { get; private set; }
public long SentBytes => Interlocked.Read(ref _sentBytes);
private long _sentBytes;
// ---- stato posseduto dal ciclo di gioco
public Subscribe? Viewport { get; set; }
public HashSet<(int Cx, int Cy)> SentChunks { get; } = [];
public Dictionary<(int Cx, int Cy), ulong> ChunkHashes { get; } = [];
public Dictionary<(EntityType Type, int Id), ulong> EntityHashes { get; } = [];
public Dictionary<int, ulong> EdgeHashes { get; } = [];
public Dictionary<int, (long Tick, byte State)> MotionSent { get; } = [];
public bool NeedsFullState { get; set; } = true;
/// <summary>Cronaca finale già inviata a questa sessione.</summary>
public bool ChronicleSent { get; set; }
public Session(ulong id, CompanyId company)
{
Id = id;
Company = company;
}
/// <summary>Riaggancio a un nuovo socket (ripresa): coda nuova, stato da rimandare per intero.</summary>
public void Attach()
{
_queue.Writer.TryComplete();
_queue = Channel.CreateUnbounded<byte[]>(new UnboundedChannelOptions { SingleReader = true });
Interlocked.Exchange(ref _pendingBytes, 0);
Connected = true;
ResetCaches();
}
public void ResetCaches()
{
SentChunks.Clear();
ChunkHashes.Clear();
EntityHashes.Clear();
EdgeHashes.Clear();
MotionSent.Clear();
NeedsFullState = true;
}
public void MarkDisconnected(long nowMs)
{
Connected = false;
DisconnectedAtMs = nowMs;
_queue.Writer.TryComplete();
}
/// <summary>Accoda un messaggio affidabile; false se la sessione va chiusa per backlog.</summary>
public bool Send(IMessage message)
{
if (!Connected) return false;
byte[] frame = Frame.Encode(message);
long pending = Interlocked.Add(ref _pendingBytes, frame.Length);
if (pending > ReliableLimitBytes)
{
_queue.Writer.TryComplete(new IOException("coda d'invio oltre il limite"));
return false;
}
return _queue.Writer.TryWrite(frame);
}
/// <summary>Accoda un messaggio scartabile (moto dei treni) se la coda è sotto soglia.</summary>
public bool SendDroppable(IMessage message)
{
if (!Connected) return false;
if (Interlocked.Read(ref _pendingBytes) > DroppableLimitBytes)
{
DroppedMotions++;
return false;
}
return Send(message);
}
/// <summary>Svuota la coda sul socket finché la sessione resta aperta.</summary>
public async Task SendLoopAsync(WebSocket socket, CancellationToken ct)
{
var reader = _queue.Reader;
while (await reader.WaitToReadAsync(ct).ConfigureAwait(false))
{
while (reader.TryRead(out var frame))
{
await socket.SendAsync(frame, WebSocketMessageType.Binary, true, ct).ConfigureAwait(false);
Interlocked.Add(ref _pendingBytes, -frame.Length);
Interlocked.Add(ref _sentBytes, frame.Length);
}
}
}
}
@@ -0,0 +1,123 @@
using System.Net.WebSockets;
using RailEnterprise.Protocol;
using RailEnterprise.Protocol.Messages;
namespace RailEnterprise.Server;
/// <summary>
/// Endpoint WebSocket <c>/ws</c>: 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.
/// </summary>
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);
}
}
/// <summary>Riceve un frame completo (anche frammentato in più parti); null alla chiusura.</summary>
private static async Task<IMessage?> 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
}
}
}
@@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}