namespace SOR.Shared.Serialization;
using System.Text.Json;
using SOR.Networking.Abstractions.Messaging;
using SOR.Shared.Networking;
///
/// IMessageSerializer implementation using System.Text.Json.
///
/// Wire format — Client to Server:
/// { "type": "chat.send", "seq": 7, "payload": { "message": "Hello" } }
///
/// Wire format — Server to Client (reply, ref = client seq):
/// { "type": "chat.send.ack", "ref": 7, "payload": { "messageId": "..." } }
///
/// Wire format — Server to Client (unsolicited push, ref = 0):
/// { "type": "game.state_update", "ref": 0, "payload": { ... } }
///
/// To swap to MessagePack:
/// 1. Create MessagePackSerializer implementing IMessageSerializer
/// 2. In SOR.Shared.ServiceRegistration: replace AddSingleton{IMessageSerializer, SystemTextJsonSerializer}
/// with AddSingleton{IMessageSerializer, MessagePackSerializer}
/// 3. Update client to send/receive MessagePack frames instead of JSON
/// 4. Nothing else changes — all handlers, all services, all tests are unaffected
///
/// Lifetime: Singleton. This class is thread-safe (no mutable state; JsonSerializerOptions
/// is immutable after construction).
///
public sealed class SystemTextJsonSerializer : IMessageSerializer
{
///
/// Shared options instance. Created once; reuse avoids repeated allocation.
/// 'static readonly' = initialized once at class load time, shared across all instances.
///
private static readonly JsonSerializerOptions Options = new()
{
// camelCase property names: C# 'SessionToken' → JSON 'sessionToken'
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
// Case-insensitive property matching for deserialization:
// JSON "SessionToken" and "sessionToken" both map to C# 'SessionToken'
PropertyNameCaseInsensitive = true,
// Compact output — no indentation in production
WriteIndented = false,
};
///
///
/// Parses the JSON envelope and extracts the type, seq, and inner payload.
/// The 'payload' JSON object is re-serialized to bytes so downstream code
/// can deserialize it independently into the handler-specific type.
///
public IClientMessage Deserialize(ReadOnlySpan wireBytes)
{
// JsonDocument provides a DOM view of JSON bytes without full deserialization.
// It is more efficient than JsonSerializer.Deserialize when we only need
// a few fields and want to defer inner payload deserialization.
// JsonDocument.Parse does not have a ReadOnlySpan{byte} overload in .NET 8.
// .ToArray() copies the span into a byte[] — minimal overhead for the parse path.
using var doc = JsonDocument.Parse(wireBytes.ToArray());
var root = doc.RootElement;
// Extract envelope fields. GetString() returns null if the property is missing
// or not a string — the ?? throw gives a clear error instead of a null ref later.
var type = root.GetProperty("type").GetString()
?? throw new JsonException("Client message missing required 'type' field.");
// TryGetProperty returns false (not an exception) if the field is absent.
// Seq defaults to 0 if not provided — older clients or fire-and-forget messages.
var seq = root.TryGetProperty("seq", out var seqEl) ? seqEl.GetInt32() : 0;
// Re-serialize the payload sub-object to bytes for handler deserialization.
// If no payload field exists, use empty bytes (handler will receive default(T)).
ReadOnlyMemory payloadBytes = ReadOnlyMemory.Empty;
if (root.TryGetProperty("payload", out var payloadEl))
{
// SerializeToUtf8Bytes allocates a new byte[] — this is fine since it
// happens once per message and the bytes are owned by RawClientMessage.
payloadBytes = JsonSerializer.SerializeToUtf8Bytes(payloadEl, Options);
}
return new RawClientMessage(type, seq, payloadBytes);
}
///
///
/// Serializes the full message envelope (type + ref + payload) to JSON bytes.
///
public ReadOnlyMemory Serialize(IServerMessage message)
{
// Anonymous type: a lightweight C# feature that creates a temporary class
// with named properties without explicitly defining a class.
// The '@' prefix on 'ref' is needed because 'ref' is a C# keyword.
var envelope = new
{
type = message.Type,
@ref = message.Ref,
payload = message.Payload,
};
return JsonSerializer.SerializeToUtf8Bytes(envelope, Options);
}
///
public T DeserializePayload(ReadOnlyMemory payload) where T : notnull
{
// Span is a stack-allocated view of the memory — no copy.
return JsonSerializer.Deserialize(payload.Span, Options)
?? throw new JsonException(
$"Payload deserialized to null for type {typeof(T).Name}. " +
"Ensure the payload JSON is not 'null'.");
}
}