Files
Rail_Enterprise/docs/PROTOCOL.md
T
Alby96andClaude Opus 5.5 c1a0049bcf
CI / Build e test (pull_request) Successful in 1m20s
CI / Immagine Docker (pull_request) Successful in 37s
Infrastruttura: nome «Rail Enterprise», CI e rilasci su Gitea, documentazione
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>
2026-11-07 11:14:54 +01:00

215 lines
17 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Rail Enterprise — Protocollo di rete
Stato: **normativo da F3**. Ogni messaggio e ogni comando ha un test di round-trip
(`tests/RailEnterprise.Tests/Protocol/ProtocolTests.cs`); decisioni in ADR 0009.
## 1. Trasporto
- WebSocket su `ws://<host>:<porta>/ws` (TLS a carico del reverse proxy: `wss://`).
- Solo messaggi binari. Un messaggio WebSocket contiene esattamente un frame.
- Porta predefinita 7400 (`RE_PORT`). Il primo messaggio del client dev'essere `Hello` entro 10 s.
## 2. Frame
```
offset tipo campo
0 u32 length lunghezza di messageId + payload (byte)
4 u16 messageId identificativo stabile del messaggio
6 ... payload corpo serializzato a mano
```
- Little endian. Dimensione massima 4 MB: frame più grandi chiudono la connessione (1009).
- `SpanWriter`/`SpanReader` con `Write(ref SpanWriter)` / `Read(ref SpanReader)` per ogni messaggio.
### Tipi elementari
| Tipo | Codifica |
|---|---|
| `bool` | 1 byte, 0 o 1 (altri valori: errore) |
| `u8/u16/u32/u64`, `i16/i32/i64` | little endian a larghezza fissa |
| `varuint` | LEB128 (lunghezze e conteggi) |
| `f32/f64` | IEEE 754 little endian |
| `string` | `varuint` lunghezza in byte + UTF-8 |
| `bytes` | `varuint` lunghezza + byte |
| `Money` | `i64` centesimi |
| `Vec2` | due `f64` (metri) |
| identità | `i32` (−1 = nessuna) |
| liste | `varuint` conteggio + elementi |
| `flags` | `u8` di estensione in coda a ogni messaggio e record (0 oggi) |
### Evoluzione
- Gli id dei messaggi, dei comandi e l'ordine dei campi non cambiano mai.
- I campi nuovi si aggiungono in coda, dopo il byte `flags`, che dice quali blocchi seguono. Un
lettore vecchio ignora i byte residui; un messaggio vecchio senza `flags` vale 0.
- `protocolVersion` (oggi 1) cresce solo per modifiche incompatibili.
- Blocchi: il bit 0 di `flags` annuncia il blocco 1 (campi della fase F4), i bit successivi i blocchi
delle fasi future. Messaggi e comandi nuovi prendono id nuovi; un lettore vecchio scarta i messaggi
che non conosce.
## 3. Handshake
```
Client → Hello { protocolVersion: u16, clientVersion: string, token: string, resumeSessionId: u64, dataHash: u64 }
Server → Welcome { sessionId: u64, summary: WorldSummary, dataHash: u64, difficulty: string }
| Reject { code: u16, reason: string }
```
- `resumeSessionId` ≠ 0 riprende una sessione disconnessa da meno di 120 s (stato rimandato per intero).
- `dataHash` ≠ 0 deve coincidere con l'hash dei dati del server.
- Codici di `Reject`: 1 versione del protocollo, 2 token errato, 3 dati diversi, 4 server pieno, 5 nessuna partita.
- `Welcome` può arrivare di nuovo durante la sessione (nuova partita o caricamento): il client azzera la copia del mondo.
`WorldSummary { seed: u64, sizeKm: i32, startYear: i32, tick: i64, date: string, companyId: i32, companyName: string,
regionId: string, widthCells: i32, heightCells: i32, cellSizeM: f64, chunkCells: i32, speed: u8, terrainHash: u64,
costMultiplier: f64 }`
## 4. Messaggi Client → Server
| id | Nome | Contenuto |
|---|---|---|
| 1 | Hello | vedi handshake |
| 2 | Ping | `nonce: u64` |
| 3 | Subscribe | `x0, y0, x1, y1: i32` (celle, estremi inclusi), `lod: u8` |
| 4 | Command | `seq: u32`, `type: u16`, `payload: bytes` (vedi sotto) |
| 5 | SetSpeed | `speed: u8` (0, 1, 2, 4, 8) |
| 6 | ListSaves | — |
| 7 | Save | `name: string` |
| 8 | Load | `saveId: string` |
| 9 | NewGame | `seed: u64`, `sizeKm: i32`, `startYear: i32` (0 = predefinito), `difficultyPreset: string`, `overrides: [(key: string, value: f64)]`, `endlessFlags: u32` |
| 10 | RequestDetail | `kind: u8` (1 cartella di manutenzione di un treno, 2 registro officina di un deposito, 3 registro degli impieghi; dalla F5: 4 scheda di una compagnia, 5 scheda di un'industria, 6 Cronaca), `target: i32` (id del treno, del deposito, della compagnia o dell'industria; ignorato per 3 e 6). Aggiunto in F4 |
### Comandi (`Command.type`, payload in ordine)
| type | Comando | Payload |
|---|---|---|
| 1 | BuildTrack | `polyline: [Vec2]`, `heightOffsetM: f64`, `allowBridges: bool`, `allowTunnels: bool`, `trackClass: string`, `doubleTrack: bool`, `electrified: bool`, `expectedCostCents: i64` (0 = non verificare) |
| 2 | RenewTrack | `edge: i32` |
| 3 | UpgradeTrack | `edge: i32`, `trackClass: string`, `doubleTrack: bool`, `electrified: bool` |
| 4 | Demolish | `target: u8` (0 arco, 1 stazione, 2 deposito, 3 segnali), `id: i32` |
| 5 | BuildStation | `position: Vec2`, `platforms: i32`, `name: bool + string` |
| 6 | BuildDepot | `position: Vec2`, `size: string`, `name: bool + string` |
| 7 | PlaceSignal | `edge: i32`, `positionM: f64` |
| 8 | BuyVehicle | `vehicleType: string`, `depot: i32`, `count: i32` |
| 9 | SellVehicle | `vehicle: i32` |
| 10 | ComposeTrain | `depot: i32`, `vehicles: [i32]`, `name: bool + string` |
| 11 | CreateLine | `name: string`, `color: string`, `stops: [LineStop]` |
| 12 | EditLine | `line: i32`, `stops: [LineStop]`, `name: bool + string` |
| 13 | AssignTrain | `train: i32`, `line: i32` (−1 = togli dal servizio) |
| 14 | SendToDepot | `train: i32`, `depot: i32` |
| 15 | SetReserve | `train: i32`, `reserve: bool` |
| 16 | SetMaintenancePolicy | `scope: u8` (0 compagnia, 1 linea, 2 treno), `target: i32`, `policy: string` |
| 17 | ScheduleService | `train: i32`, `intervention: string` |
| 18 | OrderParts | `depot: i32`, `quantity: i32`; blocco 1 (F5): `industry: i32` (ricambi ordinati per un'industria posseduta, oltre la scorta della politica) |
| 19 | TakeLoan | `amount: Money` |
| 20 | RepayLoan | `loan: i32`, `amount: Money` |
| 21 | AcceptAgreement | `agreement: i32` |
| 22 | RejectAgreement | `agreement: i32` |
| 23 | BuyGoods | `station: i32`, `good: string`, `units: i32`, `maxUnitPrice: Money` |
| 24 | SellGoods | `station: i32`, `good: string`, `units: i32`, `minUnitPrice: Money` |
| 25 | BuyIndustry | `industry: i32`, `offer: Money` |
| 26 | SetIndustryPolicy | `industry: i32`, `budget: u8` (0 nessuno, 1 base, 2 alto) |
| 27 | OverhaulIndustry | `industry: i32` |
| 28 | UpgradeIndustry | `industry: i32` |
| 29 | Ipo | `floatShare: f64` |
| 30 | BuyShares | `company: i32`, `shares: i64`, `maxPrice: Money` |
| 31 | SellShares | `company: i32`, `shares: i64`, `minPrice: Money` |
| 32 | PayDividend | `perShare: Money` |
| 33 | LaunchBid | `target: i32`, `pricePerShare: Money`, `targetShare: f64` |
| 34 | RespondBid | `bid: i32`, `accept: bool`; blocco 1 (F5): `defense: u8` (0 nessuna, 1 riacquisto, 2 dividendo straordinario, 3 cavaliere bianco), `knight: i32` |
| 35 | BuyConcession | `region: i32` |
| 36 | AcceptContract | `contract: i32` |
| 37 | FundResearch | `project: string`, `amount: Money` |
| 38 | DelegateRegion | `region: i32`, `objective: string`, `budget: Money` |
| 39 | MergeCompany | `subsidiary: i32` — fusione di una controllata dopo 360 giorni di controllo (aggiunto in F5) |
`LineStop { station: i32, load: bool, unload: bool, waitFull: bool, maxWaitDays: i32 }`. Ogni payload termina con `flags`.
I codici coincidono con l'enum `CommandType` di Core. Dalla F4 i comandi 15–18 e 21–22 sono attivi
(`policy`: `economy`, `standard`, `thorough`, oppure `inherit` per togliere l'eccezione di linea o
treno; `intervention`: `inspection`, `service`, `overhaul`; `OrderParts` fissa la scorta desiderata
del deposito). Dalla F5 sono attivi anche 25–34 e 39 (industrie, borsa, offerte, fusioni; `LaunchBid` su
una compagnia fallita è un'offerta all'asta degli attivi: prezzo per azione × azioni). Fino alla loro fase i
comandi 23–24 e 35–38 rispondono `NotImplemented`. Il server imposta l'emittente in base alla sessione.
## 5. Messaggi Server → Client
| id | Nome | Contenuto |
|---|---|---|
| 101 | Welcome | vedi handshake |
| 102 | Reject | vedi handshake |
| 103 | Pong | `nonce: u64`, `serverTick: u64` |
| 110 | MapChunk | `cx, cy, width, height: i32`, `compression: u8` (1 = Brotli), `data: bytes` = altezze `u16` (dm) + tipi `u8` + larghezza fiumi `u8` |
| 111 | EntitySnapshot | `tick: i64`, `EntityLists` |
| 112 | EntityDelta | `tick: i64`, `EntityLists` (nuovi o cambiati), `removed: [(type: u8, id: i32)]` |
| 113 | TrackWorks | `edges: [EdgeInfo]`, `removed: [i32]` (lotti sotto 1 MB) |
| 114 | TrainMotion | `trainId: i32`, `tick: i64`, `state: u8`, `condition: f32`, `speed: f32` (m/s), `lengthM: f32`, `headDistance: f64`, `segments: [(edge: i32, forward: bool, fromS: f64, toS: f64)]` |
| 120 | DailyDigest | `day: i64`, `tick: i64`, `date: string`, `cash: Money`, `netWorth: Money`, `rating: string`, `prices: [Money]`, `events: [EventInfo]`, `stateHash: u64`, `slow: bool`, `speed: u8`, `tickMs: f32` |
| 121 | MaintenanceAlert | `train: i32`, `depot: i32`, `component: string`, `condition: f32`, `dueDays: i32`, `text: string` |
| 122 | EmploymentReport | `day: i64`, `rows: [EmploymentRow]`; blocco 1: `agreements: [AgreementInfo]` (mensile, su richiesta e dopo Accept/RejectAgreement) |
| 123 | MarketTape | `day: i64`, `shares: [SharePrice]`, `bids: [BidInfo]` |
| 124 | MaintenanceCard | `train, day: i64, condition: f32, status: u8, policy: u8, policyOverride: u8, reserve, failure: u8, failedVehicle, failedComponent: string, rescueHours: f32, nextIntervention: string, nextDueDays: f32, plannedIntervention: string, maintenanceDepot, serviceKmPerDay: f32, costThisYear: Money, costLastYear: Money, failuresThisYear, failuresTotal, coveredBy, covering, vehicles: [VehicleCard], history: [MaintenanceRecordInfo]` (su richiesta, F4) |
| 125 | WorkshopRegister | `depot, day: i64, stalls, jobsStaff, staffPresent: f32, workRate: f32, spareParts, partsTarget, partsReserved, jobs: [WorkshopJobInfo], booked: [WorkshopJobInfo]` (su richiesta, F4) |
| 126 | CompanyCard | `company, totalShares: i64, treasury: i64, holdings: [HoldingInfo], priceHistory: [f64] (centesimi, mensile), history: [CompanyYearInfo], annualProfit, dividendsYear, debt, marketCap: Money, controlDays: i64, auctionMin, auctionBest: Money, auctionBestBidder, auctionEndDay: i64` (su richiesta, F5) |
| 127 | IndustryCard | `industry, margin, conditionMultiplier, wearPerDay, recoveryPerDay: f32, maintenanceCostPerDay, maintenanceSpentYear: Money, partsTarget, partsPerMonth, partsOrdered, machineryRequired, upgradeCost, valuation, cash: Money, breakdownChancePerYear: f32, stops: [IndustryStopInfo]` (su richiesta, F5) |
| 128 | Chronicle | `gameOver: bool, reason: u8 (1 fallimento, 2 scalata, 3 riscatto scaduto), text, winner, day: i64, company, foundedYear, prestige: i64, history: [CompanyYearInfo], records: [RecordInfo], highlights: [string]` (alla fine della partita e su richiesta, F5) |
| 130 | CommandResult | `seq: u32`, `type: u16`, `error: u16`, `message: string`, `created: [i32]`, `tick: i64` |
| 131 | Notification | `EventInfo` |
| 132 | Newspaper | `day: i64`, `title: string`, `articles: [(headline: string, body: string)]` |
| 133 | SaveList | `saves: [SaveInfo]` |
Record (ognuno chiude con `flags`):
- `EntityLists`: liste in quest'ordine di `CompanyInfo`, `TownInfo`, `IndustryInfo`, `HubInfo`, `NodeInfo`, `StationInfo`, `DepotInfo`, `LineInfo`, `VehicleInfo`, `TrainInfo`.
- `CompanyInfo { id, name, color, isPlayer, cash: Money, netWorth: Money, rating, tier: u8, bankrupt }`; blocco 1: `maintenancePolicy: u8` (0 economica, 1 standard, 2 accurata);
blocco 2 (F5): `personality: string, listed, sharePriceCents: f64, sentiment: f32, founderShare: f32, controlledBy: i32, merged, receivership, receivershipUntilDay: i64, annualProfit: Money`
- `TownInfo { id, name, position: Vec2, population: i32, radiusCells: f64, satisfaction: f32, services: i32 }`
- `IndustryInfo { id, type: string, name, position, footprintCells: i32, level: i32, closed, efficiency: f32, condition: f32, owner: i32 }`;
blocco 1 (F5): `budget: u8 (0 nessuno, 1 base, 2 alto), spareParts, machinery, stoppedUntilDay: i64, stopKind: u8 (1 guasto, 2 incidente, 3 revisione, 4 ammodernamento), pendingWork: u8 (1 revisione, 2 ammodernamento), partsShort: bool`
- `HubInfo { id, kind: string, name, position }`
- `NodeInfo { id, position, heightM: f64, owner, station, depot, edges: [i32] }`
- `StationInfo { id, owner, name, node, position, platforms: i32, waitingUnits: i32, industries: [i32], towns: [i32] }`
- `DepotInfo { id, owner, name, node, position, size: string }`; blocco 1: `stalls, jobsStaff, staffPercent: u8, spareParts, partsTarget, jobs, waitingParts: bool`
- `LineInfo { id, owner, name, color, stops: [LineStop] }`; blocco 1: `policy: u8` (255 = quella della compagnia)
- `VehicleInfo { id, owner, type: string, depot, train, condition: f32 }`
- `TrainInfo { id, owner, name, line, state: u8, vehicles: [i32], maxSpeedKmh: f32, lengthM: f32, load: i32, capacity: i32, depot: i32 }`;
blocco 1: `condition: u8` (componente più debole), `maintenance: u8` (0 in servizio, 1 intervento prenotato, 2 in officina,
3 guasto lieve, 4 fermo in linea, 5 rimorchiato), `reserve: bool`, `policy: u8` (255 = ereditata), `nextIntervention: string`,
`nextDueDays: i32`, `maintenanceDepot: i32`
- `EdgeInfo { id, owner, a, b, trackClass: u8, doubleTrack, electrified, state: u8, condition: f32, structureCondition: f32, progress: f32, samples: [(s, x, y, h, ground: f64, kind: u8, speedLimitKmh: f64)], signals: [f64] }`
- `EventInfo { day: i64, kind: u8, severity: u8, text, entity: u8, entityIndex: i32, company: i32 }`
- `EmploymentRow { industry, jobsWorkers, jobsStaff, workersPresent: f32, staffPresent: f32, reason, sources: [EmploymentSource { town, homeStation, line, category: u8, headcount, coverage: f32 }] }`;
blocco 1: `kind: u8` (0 industria, 1 deposito: `industry` è allora l'id del deposito), `workersReason: u8`, `staffReason: u8`
(0 nessuno, 1 nessuna stazione, 2 nessuna città entro il tempo massimo, 3 nessun lavoratore libero, 4 città senza servizi
per il personale, 5 capacità delle carrozze insufficiente), `workersReasonLine: i32`, `staffReasonLine: i32`
- `AgreementInfo { id, industry, carrier, seatsPerDay, monthlyFee: Money, state: u8 (0 proposta, 1 attiva, 2 rifiutata, 3 scaduta, 4 saltata, 5 conclusa), proposedDay: i64, startDay: i64, endDay: i64, coverage: f32, shortDays }`
- `VehicleCard { vehicle, type: string, odometerKm: f32, ageYears: f32, ageFactor: f32, components: [ComponentCard { component: string, condition: f32, wearPerDay: f32 }] }`
- `MaintenanceRecordInfo { day: i64, intervention: string, cost: Money, depot, parts }`
- `WorkshopJobInfo { train, intervention: string, inStall, started, progress: f32, days: f32, parts, queuedDay: i64 }`
- `SharePrice { company, price: Money, change: f32, listed }`; blocco 1 (F5): `priceCents: f64, outstanding: i64, freeFloat: i64, founderShare: f32, controlledBy: i32`
- `BidInfo { bid, bidder, target, pricePerShare: Money, targetShare: f64, expiresDay: i64 }`; blocco 1 (F5): `state: u8, committedShare: f64, defenses: u8 (bit per difesa usata), knight: i32, accepted: bool` (la compagnia della sessione ha aderito)
- `HoldingInfo { holder: i32 (−1 fondatore, −2 mercato, altrimenti compagnia), shares: i64 }`, `CompanyYearInfo { year, netWorth, cash, revenue, profit: Money, tier: u8, trains, trackKm: f32, sharePrice: Money }`
- `IndustryStopInfo { day: i64, days, kind: u8 }`, `RecordInfo { title, value: string, year }`
- `SaveInfo { saveId, name, gameDate, sizeBytes: i64, savedUnixMs: i64, autosave }`
## 6. Flusso e interest management
- Dopo il `Welcome` il server manda `EntitySnapshot` e tutti i `TrackWorks`; i chunk arrivano dopo
il primo `Subscribe` (viewport con un chunk di margine), una volta per sessione, e si rimandano se
cambiano.
- `EntityDelta` e `TrackWorks` incrementali dopo ogni comando riuscito e a ogni cambio di giorno.
- `TrainMotion` ogni 100 ms per i treni in moto con la testa nel viewport (più un chunk), una volta
per quelli fermi: al massimo 10 aggiornamenti al secondo per treno. Il client avanza la testa a
velocità costante tra un moto e l'altro (fattore 60: un tick = 3 s di orologio dei treni).
- `DailyDigest` e `MarketTape` (listino delle compagnie attive e offerte in corso) a ogni giorno; `EmploymentReport` a ogni mese; `Notification` per gli eventi non
informativi della compagnia della sessione; `MaintenanceAlert` quando un treno scende sotto le soglie
d'avviso (40) o critica (30) e quando un'officina resta senza ricambi.
- Dettagli su richiesta (F4): `MaintenanceCard`, `WorkshopRegister` ed `EmploymentReport` rispondono a
`RequestDetail` per entità della compagnia della sessione (le richieste per entità altrui o
inesistenti non hanno risposta). Il client li richiede mentre il pannello è aperto (una volta al
secondo): i componenti di tutti i veicoli non viaggiano nei delta delle entità. Dalla F5 anche
`CompanyCard` (qualunque compagnia), `IndustryCard` (qualunque industria aperta) e `Chronicle`; la
Cronaca arriva da sola, una volta per sessione, quando la partita del giocatore finisce.
- Backpressure: i moti si scartano oltre 256 KB in coda; oltre 64 MB di messaggi affidabili la
sessione si chiude (il client può riprenderla).
- Obiettivo di banda in regime: < 100 KB/s per client.