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,667 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Diagnostics;
|
||||
using System.Globalization;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using ViaFerrea.Core.Common;
|
||||
using ViaFerrea.Core.Data;
|
||||
using ViaFerrea.Core.Simulation;
|
||||
using ViaFerrea.Protocol;
|
||||
using ViaFerrea.Protocol.Messages;
|
||||
|
||||
namespace ViaFerrea.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;
|
||||
|
||||
// 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();
|
||||
}
|
||||
|
||||
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 => _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);
|
||||
}
|
||||
|
||||
/// <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 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);
|
||||
|
||||
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,
|
||||
});
|
||||
}
|
||||
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(EmploymentReport(w, s.Company));
|
||||
}
|
||||
_monthlyDue = false;
|
||||
_dayEvents.Clear();
|
||||
}
|
||||
|
||||
/// <summary>Registro degli impieghi della compagnia: posti serviti dai suoi treni e provenienze.</summary>
|
||||
private static EmploymentReport EmploymentReport(World w, CompanyId company)
|
||||
{
|
||||
var report = new EmploymentReport { Day = w.Clock.Day };
|
||||
foreach (var ind in w.Industries)
|
||||
{
|
||||
if (ind.Closed) continue;
|
||||
var sources = new List<EmploymentSource>();
|
||||
foreach (var c in w.Commutes)
|
||||
{
|
||||
if (c.Walking || c.Carrier != company || c.Workplace.Kind != Core.Economy.WorkplaceKind.Industry || c.Workplace.Index != ind.Id.Value) 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,
|
||||
});
|
||||
}
|
||||
if (sources.Count == 0) continue;
|
||||
report.Rows.Add(new EmploymentRow
|
||||
{
|
||||
Industry = ind.Id.Value, JobsWorkers = ind.JobsWorkers, JobsStaff = ind.JobsStaff,
|
||||
WorkersPresent = (float)ind.WorkersPresent, StaffPresent = (float)ind.StaffPresent, Sources = sources,
|
||||
});
|
||||
}
|
||||
return report;
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -1,17 +1,115 @@
|
||||
using System.Net.Http;
|
||||
using System.Text.Json.Serialization;
|
||||
using Microsoft.AspNetCore.Hosting.Server;
|
||||
using Microsoft.AspNetCore.Hosting.Server.Features;
|
||||
using ViaFerrea.Core.Data;
|
||||
using ViaFerrea.Core.Simulation;
|
||||
using ProtocolSaveInfo = ViaFerrea.Protocol.Messages.SaveInfo;
|
||||
|
||||
namespace ViaFerrea.Server;
|
||||
|
||||
/// <summary>
|
||||
/// Punto d'ingresso del server autorevole. In F0 espone solo /health; il ciclo di gioco,
|
||||
/// le sessioni WebSocket e le API dei salvataggi arrivano in F3.
|
||||
/// Server autorevole di Via Ferrea: Kestrel con WebSocket su /ws, API HTTP (/health, /metrics,
|
||||
/// /api/saves), ciclo di gioco su un thread dedicato, log JSON su stdout.
|
||||
/// </summary>
|
||||
public static class ServerProgram
|
||||
{
|
||||
public static int Main(string[] args)
|
||||
{
|
||||
var builder = WebApplication.CreateSlimBuilder(args);
|
||||
var app = builder.Build();
|
||||
app.MapGet("/health", () => Results.Text("ok"));
|
||||
app.Run();
|
||||
var config = ServerConfig.From(args, Environment.GetEnvironmentVariables());
|
||||
if (config.HealthCheck) return HealthCheck(config);
|
||||
using var app = Build(config, args);
|
||||
app.Start();
|
||||
if (config.Local)
|
||||
{
|
||||
var addresses = app.Services.GetRequiredService<IServer>().Features.Get<IServerAddressesFeature>()!.Addresses;
|
||||
int port = new Uri(addresses.First()).Port;
|
||||
Console.Out.WriteLine($"LISTENING {port}");
|
||||
Console.Out.Flush();
|
||||
}
|
||||
app.WaitForShutdown();
|
||||
return 0;
|
||||
}
|
||||
|
||||
/// <summary>Costruisce l'applicazione; i test la avviano in processo su una porta casuale.</summary>
|
||||
public static WebApplication Build(ServerConfig config, string[]? args = null, World? world = null, GameData? data = null)
|
||||
{
|
||||
var builder = WebApplication.CreateSlimBuilder(args ?? []);
|
||||
builder.Logging.ClearProviders();
|
||||
builder.Logging.AddJsonConsole(o =>
|
||||
{
|
||||
o.IncludeScopes = false;
|
||||
o.TimestampFormat = "yyyy-MM-ddTHH:mm:ss.fffZ";
|
||||
o.UseUtcTimestamp = true;
|
||||
o.JsonWriterOptions = new System.Text.Json.JsonWriterOptions { Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping };
|
||||
});
|
||||
builder.Logging.SetMinimumLevel(Enum.TryParse<LogLevel>(config.LogLevel, true, out var level) ? level : LogLevel.Information);
|
||||
builder.WebHost.UseUrls(config.Local ? "http://127.0.0.1:0" : $"http://0.0.0.0:{config.Port}");
|
||||
builder.Services.AddSingleton<HostHolder>();
|
||||
builder.Services.ConfigureHttpJsonOptions(o =>
|
||||
{
|
||||
o.SerializerOptions.TypeInfoResolverChain.Insert(0, ServerJsonContext.Default);
|
||||
o.SerializerOptions.Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping;
|
||||
});
|
||||
|
||||
var app = builder.Build();
|
||||
var log = app.Services.GetRequiredService<ILoggerFactory>().CreateLogger("ViaFerrea.Server");
|
||||
data ??= GameData.LoadDefault();
|
||||
log.LogInformation("Dati caricati: hash {Hash:x16}", data.Hash);
|
||||
var host = new GameHost(config, data, log, world);
|
||||
app.Lifetime.ApplicationStarted.Register(host.Start);
|
||||
app.Lifetime.ApplicationStopping.Register(host.Dispose);
|
||||
|
||||
app.UseWebSockets(new WebSocketOptions { KeepAliveInterval = TimeSpan.FromSeconds(30) });
|
||||
app.Map("/ws", context => SessionEndpoint.HandleAsync(context, host, log));
|
||||
app.MapGet("/health", () => host.Healthy ? Results.Text("ok") : Results.Text("ciclo di gioco fermo", statusCode: 503));
|
||||
app.MapGet("/metrics", () => Results.Text(host.Metrics(), "text/plain; version=0.0.4"));
|
||||
app.MapGet("/api/saves", () => Results.Json(host.Saves.List().Select(SaveDto.From).ToList(), Json.ListSaveDto));
|
||||
app.MapGet("/api/saves/{id}", (string id) =>
|
||||
host.Saves.Exists(id) ? Results.File(host.Saves.PathOf(id), "application/octet-stream", Path.GetFileName(host.Saves.PathOf(id))) : Results.NotFound());
|
||||
app.MapPost("/api/saves", async (string? name) =>
|
||||
{
|
||||
var info = await host.InvokeAsync(_ => host.SaveNow(string.IsNullOrWhiteSpace(name) ? "partita" : name));
|
||||
return Results.Json(SaveDto.From(info), Json.SaveDto, statusCode: StatusCodes.Status201Created);
|
||||
});
|
||||
app.Services.GetRequiredService<HostHolder>().Host = host;
|
||||
return app;
|
||||
}
|
||||
|
||||
private static readonly ServerJsonContext Json = new(new System.Text.Json.JsonSerializerOptions
|
||||
{
|
||||
PropertyNamingPolicy = System.Text.Json.JsonNamingPolicy.CamelCase,
|
||||
Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
|
||||
});
|
||||
|
||||
private static int HealthCheck(ServerConfig config)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(4) };
|
||||
var response = http.GetAsync($"http://127.0.0.1:{config.Port}/health").GetAwaiter().GetResult();
|
||||
return response.IsSuccessStatusCode ? 0 : 1;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Riferimento al GameHost per i test in processo.</summary>
|
||||
public sealed class HostHolder
|
||||
{
|
||||
public GameHost? Host { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>Descrizione di un salvataggio nell'API HTTP.</summary>
|
||||
public sealed record SaveDto(string Id, string Name, string GameDate, long SizeBytes, long SavedUnixMs, bool Autosave)
|
||||
{
|
||||
public static SaveDto From(ProtocolSaveInfo s) => new(s.SaveId, s.Name, s.GameDate, s.SizeBytes, s.SavedUnixMs, s.Autosave);
|
||||
}
|
||||
|
||||
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, WriteIndented = false)]
|
||||
[JsonSerializable(typeof(SaveDto))]
|
||||
[JsonSerializable(typeof(List<SaveDto>))]
|
||||
internal sealed partial class ServerJsonContext : JsonSerializerContext;
|
||||
@@ -0,0 +1,256 @@
|
||||
using ViaFerrea.Core.Common;
|
||||
using ViaFerrea.Core.Economy;
|
||||
using ViaFerrea.Core.Rail;
|
||||
using ViaFerrea.Core.Simulation;
|
||||
using ViaFerrea.Protocol;
|
||||
using ViaFerrea.Protocol.Messages;
|
||||
|
||||
namespace ViaFerrea.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,
|
||||
});
|
||||
}
|
||||
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)i.Condition, Owner = i.Owner.IsValid ? i.Owner.Value : -1,
|
||||
});
|
||||
}
|
||||
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;
|
||||
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 });
|
||||
}
|
||||
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() });
|
||||
}
|
||||
foreach (var v in w.Vehicles)
|
||||
{
|
||||
if (v.Sold) continue;
|
||||
double cond = 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;
|
||||
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,
|
||||
});
|
||||
}
|
||||
return e;
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
using System.Globalization;
|
||||
using ViaFerrea.Core.Data;
|
||||
using ViaFerrea.Core.Persistence;
|
||||
using ViaFerrea.Core.Simulation;
|
||||
using ProtocolSaveInfo = ViaFerrea.Protocol.Messages.SaveInfo;
|
||||
|
||||
namespace ViaFerrea.Server;
|
||||
|
||||
/// <summary>
|
||||
/// Salvataggi in <c>$VF_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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
using System.Collections;
|
||||
|
||||
namespace ViaFerrea.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>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("VF_DATA_DIR")
|
||||
?? (local ? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "ViaFerrea") : "/data");
|
||||
return new ServerConfig
|
||||
{
|
||||
Local = local,
|
||||
HealthCheck = args.Contains("--healthcheck"),
|
||||
Port = int.TryParse(Arg("--port") ?? Env("VF_PORT"), out int port) ? port : 7400,
|
||||
Token = Arg("--token") ?? Env("VF_TOKEN") ?? "",
|
||||
DataDir = dataDir,
|
||||
TickMs = int.TryParse(Env("VF_TICK_MS"), out int tick) && tick > 0 ? tick : 50,
|
||||
AutosaveMinutes = int.TryParse(Env("VF_AUTOSAVE_MIN"), out int auto) ? auto : 10,
|
||||
Seed = ulong.TryParse(Env("VF_SEED"), out ulong seed) ? seed : 1,
|
||||
MapSizeKm = int.TryParse(Env("VF_MAP_SIZE"), out int size) ? size : 128,
|
||||
Difficulty = Env("VF_DIFFICULTY") ?? "imprenditore",
|
||||
LogLevel = Env("VF_LOG_LEVEL") ?? "Information",
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
using System.Net.WebSockets;
|
||||
using System.Threading.Channels;
|
||||
using ViaFerrea.Core.Common;
|
||||
using ViaFerrea.Protocol;
|
||||
using ViaFerrea.Protocol.Messages;
|
||||
|
||||
namespace ViaFerrea.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;
|
||||
|
||||
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 ViaFerrea.Protocol;
|
||||
using ViaFerrea.Protocol.Messages;
|
||||
|
||||
namespace ViaFerrea.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
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user