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>
52 lines
2.0 KiB
C#
52 lines
2.0 KiB
C#
using System.Buffers.Binary;
|
|
using RailEnterprise.Protocol.Messages;
|
|
|
|
namespace RailEnterprise.Protocol;
|
|
|
|
/// <summary>
|
|
/// Frame <c>[u32 length][u16 messageId][payload]</c>, little endian; length conta messageId e
|
|
/// payload. Un messaggio WebSocket binario contiene esattamente un frame.
|
|
/// </summary>
|
|
public static class Frame
|
|
{
|
|
public const int HeaderSize = 6;
|
|
public const int MaxFrameBytes = 4 * 1024 * 1024;
|
|
public const int MaxLength = MaxFrameBytes - 4;
|
|
|
|
/// <summary>Versione del protocollo: cresce solo per modifiche incompatibili.</summary>
|
|
public const ushort ProtocolVersion = 1;
|
|
|
|
public static byte[] Encode(IMessage message)
|
|
{
|
|
var w = new SpanWriter(256);
|
|
w.U32(0);
|
|
w.U16((ushort)message.Id);
|
|
message.Write(ref w);
|
|
int length = w.Length - 4;
|
|
if (length > MaxLength) throw new ProtocolException($"frame troppo grande: {w.Length} byte");
|
|
w.PatchU32(0, (uint)length);
|
|
return w.ToArray();
|
|
}
|
|
|
|
/// <summary>Lunghezza totale del frame che inizia in data, se l'intestazione è completa.</summary>
|
|
public static bool TryReadLength(ReadOnlySpan<byte> data, out int frameBytes)
|
|
{
|
|
frameBytes = 0;
|
|
if (data.Length < 4) return false;
|
|
uint length = BinaryPrimitives.ReadUInt32LittleEndian(data);
|
|
if (length < 2 || length > MaxLength) throw new ProtocolException($"lunghezza del frame non valida: {length}");
|
|
frameBytes = (int)length + 4;
|
|
return true;
|
|
}
|
|
|
|
public static IMessage Decode(ReadOnlySpan<byte> frame)
|
|
{
|
|
if (frame.Length < HeaderSize) throw new ProtocolException("frame troppo corto");
|
|
uint length = BinaryPrimitives.ReadUInt32LittleEndian(frame);
|
|
if (length > MaxLength || length + 4 != frame.Length) throw new ProtocolException($"lunghezza del frame incoerente: {length} su {frame.Length} byte");
|
|
var id = (MessageId)BinaryPrimitives.ReadUInt16LittleEndian(frame[4..]);
|
|
var r = new SpanReader(frame[HeaderSize..]);
|
|
return MessageCodec.Read(id, ref r);
|
|
}
|
|
}
|