Implements the modular networking layer for SOR Server: - SOR.Networking.Abstractions: pure interfaces (ITransport, IClientConnection, IMessageSerializer, IMessageDispatcher, IMessageHandler, IEventBus, IClientPush) - SOR.Networking.WebSocket: ITransport + IClientConnection over System.Net.WebSockets - SOR.Networking.Nats: IEventBus over NATS.Net (INatsConnection) - SOR.Networking.Redis: IClientPush over Redis Pub/Sub - SOR.Shared: ServiceResult<T>, RedisKeys, NatsSubjects, ServerMessage, JSON serializer - SOR.Shared.Proto: auth.proto with gRPC AuthService contract - SOR.Gateway: accept loop, auth handshake, dispatcher, Redis push subscriber - SOR.Auth: stub gRPC handler (placeholder responses) - SOR.Host: multi-service runner via ENABLED_SERVICES env var; wires all DI All concrete implementations are wired exclusively in SOR.Host — every transport, broker, and push implementation can be swapped by changing only Program.cs. dotnet build SOR.slnx → 0 errors, 0 warnings Generated with [Claude Code](https://claude.ai/code) via [Happy](https://happy.engineering) Co-Authored-By: Claude <noreply@anthropic.com> Co-Authored-By: Happy <yesreply@happy.engineering>
115 lines
5.1 KiB
C#
115 lines
5.1 KiB
C#
namespace SOR.Shared.Serialization;
|
|
|
|
using System.Text.Json;
|
|
using SOR.Networking.Abstractions.Messaging;
|
|
using SOR.Shared.Networking;
|
|
|
|
/// <summary>
|
|
/// 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).
|
|
/// </summary>
|
|
public sealed class SystemTextJsonSerializer : IMessageSerializer
|
|
{
|
|
/// <summary>
|
|
/// Shared options instance. Created once; reuse avoids repeated allocation.
|
|
/// 'static readonly' = initialized once at class load time, shared across all instances.
|
|
/// </summary>
|
|
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,
|
|
};
|
|
|
|
/// <inheritdoc/>
|
|
/// <remarks>
|
|
/// 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.
|
|
/// </remarks>
|
|
public IClientMessage Deserialize(ReadOnlySpan<byte> 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<byte> payloadBytes = ReadOnlyMemory<byte>.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);
|
|
}
|
|
|
|
/// <inheritdoc/>
|
|
/// <remarks>
|
|
/// Serializes the full message envelope (type + ref + payload) to JSON bytes.
|
|
/// </remarks>
|
|
public ReadOnlyMemory<byte> 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);
|
|
}
|
|
|
|
/// <inheritdoc/>
|
|
public T DeserializePayload<T>(ReadOnlyMemory<byte> payload) where T : notnull
|
|
{
|
|
// Span<byte> is a stack-allocated view of the memory — no copy.
|
|
return JsonSerializer.Deserialize<T>(payload.Span, Options)
|
|
?? throw new JsonException(
|
|
$"Payload deserialized to null for type {typeof(T).Name}. " +
|
|
"Ensure the payload JSON is not 'null'.");
|
|
}
|
|
}
|