Fix NATS serialization: use System.Text.Json for custom event types

NatsUtf8PrimitivesSerializer (the default) can only handle primitives and
strings, causing "Can't serialize GameStartedEvent" at runtime.

Add NatsJsonSerializer<T> implementing INatsSerialize<T>/INatsDeserialize<T>
using System.Text.Json, and pass it explicitly to PublishAsync/SubscribeAsync
in NatsEventBus so all custom NATS event payloads serialize as JSON.

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>
This commit is contained in:
dingo
2026-03-07 14:15:45 -05:00
co-authored by Claude Happy
parent dc9b64dc6f
commit ece3eaa3be
2 changed files with 42 additions and 2 deletions
@@ -48,7 +48,9 @@ public sealed class NatsEventBus : IEventBus
{
_logger.LogDebug("Publishing event to NATS subject {Subject}", subject);
await _nats.PublishAsync(subject, payload, cancellationToken: cancellationToken);
await _nats.PublishAsync(subject, payload,
serializer: NatsJsonSerializer<T>.Default,
cancellationToken: cancellationToken);
}
/// <inheritdoc/>
@@ -88,7 +90,11 @@ public sealed class NatsEventBus : IEventBus
// SubscribeAsync returns IAsyncEnumerable{NatsMsg{T}}.
// NatsMsg{T} is the NATS envelope containing the deserialized data plus metadata.
await foreach (var msg in _nats
.SubscribeAsync<T>(subject, cancellationToken: cancellationToken)
.SubscribeAsync<T>(subject,
queueGroup: null,
serializer: NatsJsonSerializer<T>.Default,
opts: default,
cancellationToken: cancellationToken)
.WithCancellation(cancellationToken))
{
// Skip null data (can occur for empty NATS messages or deserialization failures).
@@ -0,0 +1,34 @@
namespace SOR.Networking.Nats;
using System.Buffers;
using System.Text.Json;
using NATS.Client.Core;
/// <summary>
/// System.Text.Json serializer/deserializer for NATS messages.
///
/// NATS.Client.Core 2.3.0 does not ship a ready-made JSON registry.
/// This class implements both <see cref="INatsSerialize{T}"/> and
/// <see cref="INatsDeserialize{T}"/> so it can be passed to
/// <c>PublishAsync(serializer:)</c> and <c>SubscribeAsync(deserializer:)</c>.
/// </summary>
internal sealed class NatsJsonSerializer<T> : INatsSerialize<T>, INatsDeserialize<T>
{
public static readonly NatsJsonSerializer<T> Default = new();
private static readonly JsonSerializerOptions Options =
new(JsonSerializerDefaults.Web);
public void Serialize(IBufferWriter<byte> bufferWriter, T value)
{
var writer = new Utf8JsonWriter(bufferWriter);
JsonSerializer.Serialize(writer, value, Options);
writer.Flush();
}
public T? Deserialize(in ReadOnlySequence<byte> buffer)
{
var reader = new Utf8JsonReader(buffer);
return JsonSerializer.Deserialize<T>(ref reader, Options);
}
}