-
Notifications
You must be signed in to change notification settings - Fork 58
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
* Fix JS API deserializer * Format * Fix JetStream API serialization with typed results Replace JsonDocument-based responses with strongly-typed `NatsJSApiResult<T>` for improved type safety and error handling. Added new deserialization logic and tests to cover valid responses, errors, and edge cases like empty buffers. * Format
- Loading branch information
Showing
4 changed files
with
228 additions
and
27 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,59 @@ | ||
using System.Runtime.CompilerServices; | ||
using NATS.Client.JetStream.Models; | ||
|
||
namespace NATS.Client.JetStream.Internal; | ||
|
||
internal readonly struct NatsJSApiResult<T> | ||
{ | ||
private readonly T? _value; | ||
private readonly ApiError? _error; | ||
private readonly Exception? _exception; | ||
|
||
public NatsJSApiResult(T value) | ||
{ | ||
_value = value; | ||
_error = null; | ||
_exception = null; | ||
} | ||
|
||
public NatsJSApiResult(ApiError error) | ||
{ | ||
_value = default; | ||
_error = error; | ||
_exception = null; | ||
} | ||
|
||
public NatsJSApiResult(Exception exception) | ||
{ | ||
_value = default; | ||
_error = null; | ||
_exception = exception; | ||
} | ||
|
||
public T Value => _value ?? ThrowValueIsNotSetException(); | ||
|
||
public ApiError Error => _error ?? ThrowErrorIsNotSetException(); | ||
|
||
public Exception Exception => _exception ?? ThrowExceptionIsNotSetException(); | ||
|
||
public bool Success => _error == null && _exception == null; | ||
|
||
public bool HasError => _error != null; | ||
|
||
public bool HasException => _exception != null; | ||
|
||
public static implicit operator NatsJSApiResult<T>(T value) => new(value); | ||
|
||
public static implicit operator NatsJSApiResult<T>(ApiError error) => new(error); | ||
|
||
public static implicit operator NatsJSApiResult<T>(Exception exception) => new(exception); | ||
|
||
private static T ThrowValueIsNotSetException() => throw CreateInvalidOperationException("Result value is not set"); | ||
|
||
private static ApiError ThrowErrorIsNotSetException() => throw CreateInvalidOperationException("Result error is not set"); | ||
|
||
private static Exception ThrowExceptionIsNotSetException() => throw CreateInvalidOperationException("Result exception is not set"); | ||
|
||
[MethodImpl(MethodImplOptions.NoInlining)] | ||
private static Exception CreateInvalidOperationException(string message) => new InvalidOperationException(message); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
128 changes: 128 additions & 0 deletions
128
tests/NATS.Client.JetStream.Tests/JetStreamApiSerializerTest.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,128 @@ | ||
using System.Buffers; | ||
using System.Text; | ||
using NATS.Client.Core2.Tests; | ||
using NATS.Client.JetStream.Internal; | ||
using NATS.Client.JetStream.Models; | ||
using JsonSerializer = System.Text.Json.JsonSerializer; | ||
|
||
namespace NATS.Client.JetStream.Tests; | ||
|
||
[Collection("nats-server")] | ||
public class JetStreamApiSerializerTest | ||
{ | ||
private readonly ITestOutputHelper _output; | ||
private readonly NatsServerFixture _server; | ||
|
||
public JetStreamApiSerializerTest(ITestOutputHelper output, NatsServerFixture server) | ||
{ | ||
_output = output; | ||
_server = server; | ||
} | ||
|
||
[Fact] | ||
public async Task Should_respect_buffers_lifecycle() | ||
{ | ||
await using var nats = new NatsConnection(new NatsOpts { Url = _server.Url }); | ||
var prefix = _server.GetNextId(); | ||
var js = new NatsJSContext(nats); | ||
var apiSubject = $"{prefix}.js.fake.api"; | ||
var dataSubject = $"{prefix}.data"; | ||
|
||
var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30)); | ||
var ctsDone = CancellationTokenSource.CreateLinkedTokenSource(cts.Token); | ||
|
||
List<Task> tasks = new(); | ||
|
||
// Keep reader buffers busy with lots of data which should not be | ||
// kept around and used by the JsonDocument deserializer. | ||
// Data reader | ||
tasks.Add(Task.Run( | ||
async () => | ||
{ | ||
await foreach (var unused in nats.SubscribeAsync<string>(dataSubject, cancellationToken: ctsDone.Token)) | ||
{ | ||
} | ||
}, | ||
cts.Token)); | ||
|
||
// Data writer | ||
tasks.Add(Task.Run( | ||
async () => | ||
{ | ||
var data = new string('x', 1024); | ||
while (ctsDone.IsCancellationRequested == false) | ||
{ | ||
await nats.PublishAsync(dataSubject, data, cancellationToken: ctsDone.Token); | ||
} | ||
}, | ||
cts.Token)); | ||
|
||
// Fake JS API responder | ||
tasks.Add(Task.Run( | ||
async () => | ||
{ | ||
var json = JsonSerializer.Serialize(new AccountInfoResponse { Consumers = 1234 }); | ||
await foreach (var msg in nats.SubscribeAsync<object>(apiSubject, cancellationToken: ctsDone.Token)) | ||
{ | ||
await msg.ReplyAsync(json, cancellationToken: cts.Token); | ||
} | ||
}, | ||
cts.Token)); | ||
|
||
// Fake JS API requester | ||
tasks.Add(Task.Run( | ||
async () => | ||
{ | ||
for (var i = 0; i < 100; i++) | ||
{ | ||
if (ctsDone.IsCancellationRequested) | ||
return; | ||
|
||
try | ||
{ | ||
var result = await js.TryJSRequestAsync<object, AccountInfoResponse>(apiSubject, null, ctsDone.Token); | ||
} | ||
catch | ||
{ | ||
ctsDone.Cancel(); | ||
throw; | ||
} | ||
} | ||
|
||
ctsDone.Cancel(); | ||
}, | ||
cts.Token)); | ||
|
||
try | ||
{ | ||
await Task.WhenAll(tasks); | ||
} | ||
catch (TaskCanceledException) | ||
{ | ||
} | ||
} | ||
|
||
[Fact] | ||
public void Deserialize_value() | ||
{ | ||
var serializer = NatsJSJsonDocumentSerializer<AccountInfoResponse>.Default; | ||
var result = serializer.Deserialize(new ReadOnlySequence<byte>(Encoding.UTF8.GetBytes("""{"memory":1}"""))); | ||
result.Value.Memory.Should().Be(1); | ||
} | ||
|
||
[Fact] | ||
public void Deserialize_empty_buffer() | ||
{ | ||
var serializer = NatsJSJsonDocumentSerializer<AccountInfoResponse>.Default; | ||
var result = serializer.Deserialize(ReadOnlySequence<byte>.Empty); | ||
result.Exception.Message.Should().Be("Buffer is empty"); | ||
} | ||
|
||
[Fact] | ||
public void Deserialize_error() | ||
{ | ||
var serializer = NatsJSJsonDocumentSerializer<AccountInfoResponse>.Default; | ||
var result = serializer.Deserialize(new ReadOnlySequence<byte>(Encoding.UTF8.GetBytes("""{"error":{"code":2}}"""))); | ||
result.Error.Code.Should().Be(2); | ||
} | ||
} |