diff --git a/README.md b/README.md index 2840bf4dd..f063e863f 100644 --- a/README.md +++ b/README.md @@ -59,7 +59,7 @@ for (int i = 0; i < 10; i++) You should also hook your logger to `NatsConnection` to make sure all is working as expected or to get help diagnosing any issues you might have: ```csharp -var options = NatsOptions.Default with { LoggerFactory = new MinimumConsoleLoggerFactory(LogLevel.Error) }; +var options = NatsOpts.Default with { LoggerFactory = new MinimumConsoleLoggerFactory(LogLevel.Error) }; await using var nats = new NatsConnection(options); ``` diff --git a/docs/index.md b/docs/index.md index a41d92ac0..f51567bfa 100644 --- a/docs/index.md +++ b/docs/index.md @@ -57,7 +57,7 @@ for (int i = 0; i < 10; i++) You should also hook your logger to `NatsConnection` to make sure all is working as expected or to get help diagnosing any issues you might have: ```csharp -var options = NatsOptions.Default with { LoggerFactory = new MinimumConsoleLoggerFactory(LogLevel.Error) }; +var options = NatsOpts.Default with { LoggerFactory = new MinimumConsoleLoggerFactory(LogLevel.Error) }; await using var nats = new NatsConnection(options); ``` diff --git a/sandbox/BlazorWasm/Client/Program.cs b/sandbox/BlazorWasm/Client/Program.cs index 235d9d187..510188b84 100644 --- a/sandbox/BlazorWasm/Client/Program.cs +++ b/sandbox/BlazorWasm/Client/Program.cs @@ -8,6 +8,6 @@ builder.RootComponents.Add("#app"); builder.RootComponents.Add("head::after"); -builder.Services.AddNats(configureOptions: opt => opt with { Url = "ws://localhost:4280", Name = "BlazorClient" }); +builder.Services.AddNats(configureOpts: opt => opt with { Url = "ws://localhost:4280", Name = "BlazorClient" }); await builder.Build().RunAsync(); diff --git a/sandbox/BlazorWasm/Server/Program.cs b/sandbox/BlazorWasm/Server/Program.cs index e6a3bce4b..43558a680 100644 --- a/sandbox/BlazorWasm/Server/Program.cs +++ b/sandbox/BlazorWasm/Server/Program.cs @@ -7,7 +7,7 @@ // Add services to the container. builder.Services.AddControllersWithViews(); builder.Services.AddRazorPages(); -builder.Services.AddNats(configureOptions: opt => opt with { Url = "localhost:4222", Name = "BlazorServer" }); +builder.Services.AddNats(configureOpts: opt => opt with { Url = "localhost:4222", Name = "BlazorServer" }); builder.Services.AddHostedService(); var app = builder.Build(); diff --git a/sandbox/ConsoleApp/Program.cs b/sandbox/ConsoleApp/Program.cs index 87532bcc1..d670013f2 100644 --- a/sandbox/ConsoleApp/Program.cs +++ b/sandbox/ConsoleApp/Program.cs @@ -6,7 +6,7 @@ var builder = ConsoleApp.CreateBuilder(args); builder.ConfigureServices(services => { - services.AddNats(poolSize: 4, configureOptions: opt => opt with { Url = "localhost:4222", Name = "MyClient" }); + services.AddNats(poolSize: 4, configureOpts: opt => opt with { Url = "localhost:4222", Name = "MyClient" }); }); // create connection(default, connect to nats://localhost:4222) @@ -58,7 +58,7 @@ Url = "nats://127.0.0.1:9999", LoggerFactory = new MinimumConsoleLoggerFactory(LogLevel.Information), Echo = true, - AuthOptions = NatsAuthOptions.Default with + AuthOpts = NatsAuthOpts.Default with { Username = "foo", Password = "bar", diff --git a/sandbox/ConsoleApp2/Program.cs b/sandbox/ConsoleApp2/Program.cs index aaa971a5e..443a24dc3 100644 --- a/sandbox/ConsoleApp2/Program.cs +++ b/sandbox/ConsoleApp2/Program.cs @@ -4,7 +4,7 @@ var natsKey1 = new NatsKey("subject1"); var natsKey2 = new NatsKey("subject2"); -await using var subConnection1 = new NatsConnection(NatsOptions.Default with +await using var subConnection1 = new NatsConnection(NatsOpts.Default with { Url = "localhost:4222" }); @@ -20,7 +20,7 @@ Console.WriteLine($"\tSUB1:{x}"); }); -await using var subConnection2 = new NatsConnection(NatsOptions.Default with +await using var subConnection2 = new NatsConnection(NatsOpts.Default with { Url = "localhost:4222" }); @@ -41,14 +41,14 @@ Task.Run(async () => { - await using var pubConnection1 = new NatsConnection(NatsOptions.Default with + await using var pubConnection1 = new NatsConnection(NatsOpts.Default with { Url = "localhost:4222" }); await pubConnection1.ConnectAsync(); - await using var pubConnection2 = new NatsConnection(NatsOptions.Default with + await using var pubConnection2 = new NatsConnection(NatsOpts.Default with { Url = "localhost:4222" }); diff --git a/sandbox/Example.JetStream.PullConsumer/Program.cs b/sandbox/Example.JetStream.PullConsumer/Program.cs index 89da628b4..ad536fcb0 100644 --- a/sandbox/Example.JetStream.PullConsumer/Program.cs +++ b/sandbox/Example.JetStream.PullConsumer/Program.cs @@ -1,4 +1,4 @@ -using System.Diagnostics; +using System.Diagnostics; using Example.JetStream.PullConsumer; using Microsoft.Extensions.Logging; using NATS.Client.Core; @@ -62,7 +62,10 @@ void Report(int i, Stopwatch sw, string data) var nextOpts = new NatsJSNextOpts { - Expires = expires, IdleHeartbeat = idle, Serializer = new RawDataSerializer(), ErrorHandler = ErrorHandler, + Expires = expires, + IdleHeartbeat = idle, + Serializer = new RawDataSerializer(), + ErrorHandler = ErrorHandler, }; var stopwatch = Stopwatch.StartNew(); diff --git a/sandbox/Example.JetStream.PullConsumer/RawData.cs b/sandbox/Example.JetStream.PullConsumer/RawData.cs index 348147521..89e12b76e 100644 --- a/sandbox/Example.JetStream.PullConsumer/RawData.cs +++ b/sandbox/Example.JetStream.PullConsumer/RawData.cs @@ -1,4 +1,4 @@ -using System.Text; +using System.Text; namespace Example.JetStream.PullConsumer; diff --git a/sandbox/Example.JetStream.PullConsumer/RawDataSerializer.cs b/sandbox/Example.JetStream.PullConsumer/RawDataSerializer.cs index c738fd0be..6d26036a0 100644 --- a/sandbox/Example.JetStream.PullConsumer/RawDataSerializer.cs +++ b/sandbox/Example.JetStream.PullConsumer/RawDataSerializer.cs @@ -1,4 +1,4 @@ -using System.Buffers; +using System.Buffers; using NATS.Client.Core; namespace Example.JetStream.PullConsumer; diff --git a/src/NATS.Client.Core/Commands/ConnectCommand.cs b/src/NATS.Client.Core/Commands/ConnectCommand.cs index e6265ce81..9cfe438c2 100644 --- a/src/NATS.Client.Core/Commands/ConnectCommand.cs +++ b/src/NATS.Client.Core/Commands/ConnectCommand.cs @@ -4,20 +4,20 @@ namespace NATS.Client.Core.Commands; internal sealed class AsyncConnectCommand : AsyncCommandBase { - private ClientOptions? _clientOptions; + private ClientOpts? _clientOpts; private AsyncConnectCommand() { } - public static AsyncConnectCommand Create(ObjectPool pool, ClientOptions connectOptions, CancellationTimer timer) + public static AsyncConnectCommand Create(ObjectPool pool, ClientOpts connectOpts, CancellationTimer timer) { if (!TryRent(pool, out var result)) { result = new AsyncConnectCommand(); } - result._clientOptions = connectOptions; + result._clientOpts = connectOpts; result.SetCancellationTimer(timer); return result; @@ -25,11 +25,11 @@ public static AsyncConnectCommand Create(ObjectPool pool, ClientOptions connectO public override void Write(ProtocolWriter writer) { - writer.WriteConnect(_clientOptions!); + writer.WriteConnect(_clientOpts!); } protected override void Reset() { - _clientOptions = null; + _clientOpts = null; } } diff --git a/src/NATS.Client.Core/Commands/ProtocolWriter.cs b/src/NATS.Client.Core/Commands/ProtocolWriter.cs index fae0e67fc..f080c27e9 100644 --- a/src/NATS.Client.Core/Commands/ProtocolWriter.cs +++ b/src/NATS.Client.Core/Commands/ProtocolWriter.cs @@ -24,12 +24,12 @@ public ProtocolWriter(FixedArrayBufferWriter writer) // https://docs.nats.io/reference/reference-protocols/nats-protocol#connect // CONNECT {["option_name":option_value],...} - public void WriteConnect(ClientOptions options) + public void WriteConnect(ClientOpts opts) { WriteConstant(CommandConstants.ConnectWithPadding); var jsonWriter = new Utf8JsonWriter(_writer); - JsonSerializer.Serialize(jsonWriter, options, JsonContext.Default.ClientOptions); + JsonSerializer.Serialize(jsonWriter, opts, JsonContext.Default.ClientOpts); WriteConstant(CommandConstants.NewLine); } diff --git a/src/NATS.Client.Core/INatsConnection.cs b/src/NATS.Client.Core/INatsConnection.cs index d99db6a42..cce160449 100644 --- a/src/NATS.Client.Core/INatsConnection.cs +++ b/src/NATS.Client.Core/INatsConnection.cs @@ -92,7 +92,7 @@ public interface INatsConnection /// /// Response can be (null) or one . /// Reply option's max messages will be set to 1. - /// if reply option's timeout is not defined then it will be set to NatsOptions.RequestTimeout. + /// if reply option's timeout is not defined then it will be set to NatsOpts.RequestTimeout. /// ValueTask?> RequestAsync( string subject, @@ -114,7 +114,7 @@ public interface INatsConnection /// /// Response can be (null) or one . /// Reply option's max messages will be set to 1 (one). - /// if reply option's timeout is not defined then it will be set to NatsOptions.RequestTimeout. + /// if reply option's timeout is not defined then it will be set to NatsOpts.RequestTimeout. /// ValueTask RequestAsync( string subject, @@ -136,7 +136,7 @@ public interface INatsConnection /// An asynchronous enumerable of objects /// Raised when cancellation token is used /// - /// if reply option's timeout is not defined then it will be set to NatsOptions.RequestTimeout. + /// if reply option's timeout is not defined then it will be set to NatsOpts.RequestTimeout. /// IAsyncEnumerable> RequestManyAsync( string subject, @@ -156,7 +156,7 @@ public interface INatsConnection /// An asynchronous enumerable of objects /// Raised when cancellation token is used /// - /// if reply option's timeout is not defined then it will be set to NatsOptions.RequestTimeout. + /// if reply option's timeout is not defined then it will be set to NatsOpts.RequestTimeout. /// IAsyncEnumerable RequestManyAsync( string subject, diff --git a/src/NATS.Client.Core/INatsConnectionPool.cs b/src/NATS.Client.Core/INatsConnectionPool.cs index cb332ccf3..524e1be7d 100644 --- a/src/NATS.Client.Core/INatsConnectionPool.cs +++ b/src/NATS.Client.Core/INatsConnectionPool.cs @@ -1,4 +1,4 @@ -namespace NATS.Client.Core; +namespace NATS.Client.Core; public interface INatsConnectionPool : IAsyncDisposable { diff --git a/src/NATS.Client.Core/Internal/ClientOptions.cs b/src/NATS.Client.Core/Internal/ClientOpts.cs similarity index 89% rename from src/NATS.Client.Core/Internal/ClientOptions.cs rename to src/NATS.Client.Core/Internal/ClientOpts.cs index 6ecbf74ac..65000dbf9 100644 --- a/src/NATS.Client.Core/Internal/ClientOptions.cs +++ b/src/NATS.Client.Core/Internal/ClientOpts.cs @@ -3,24 +3,24 @@ namespace NATS.Client.Core.Internal; -// SYSLIB1037: The type 'ClientOptions' defines init-only properties, +// SYSLIB1037: The type 'ClientOpts' defines init-only properties, // deserialization of which is currently not supported in source generation mode #pragma warning disable SYSLIB1037 // These connections options are serialized and sent to the server. // https://github.com/nats-io/nats-server/blob/a23b1b7/server/client.go#L536 -internal sealed class ClientOptions +internal sealed class ClientOpts { - private ClientOptions(NatsOpts opts) + private ClientOpts(NatsOpts opts) { Name = opts.Name; Echo = opts.Echo; Verbose = opts.Verbose; Headers = opts.Headers; - Username = opts.AuthOptions.Username; - Password = opts.AuthOptions.Password; - AuthToken = opts.AuthOptions.Token; - JWT = opts.AuthOptions.Jwt; + Username = opts.AuthOpts.Username; + Password = opts.AuthOpts.Password; + AuthToken = opts.AuthOpts.Token; + JWT = opts.AuthOpts.Jwt; } /// Optional boolean. If set to true, the server (version 1.2.0+) will not send originating messages from this connection to its own subscriptions. Clients should set this to true only for server supporting this feature, which is when proto in the INFO protocol is set to at least 1. @@ -90,14 +90,14 @@ private ClientOptions(NatsOpts opts) [JsonPropertyName("no_responders")] public bool NoResponders { get; init; } = false; - public static ClientOptions Create(NatsOpts opts) + public static ClientOpts Create(NatsOpts opts) { - return new ClientOptions(opts); + return new ClientOpts(opts); } private static string GetAssemblyVersion() { - var asm = typeof(ClientOptions); + var asm = typeof(ClientOpts); var version = "1.0.0"; var infoVersion = asm!.GetCustomAttribute(); if (infoVersion != null) diff --git a/src/NATS.Client.Core/Internal/JsonContext.cs b/src/NATS.Client.Core/Internal/JsonContext.cs index 7df081ee4..3938005b7 100644 --- a/src/NATS.Client.Core/Internal/JsonContext.cs +++ b/src/NATS.Client.Core/Internal/JsonContext.cs @@ -4,7 +4,7 @@ namespace NATS.Client.Core.Internal; [JsonSourceGenerationOptions(DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull)] [JsonSerializable(typeof(ServerInfo), GenerationMode = JsonSourceGenerationMode.Metadata)] -[JsonSerializable(typeof(ClientOptions), GenerationMode = JsonSourceGenerationMode.Serialization)] +[JsonSerializable(typeof(ClientOpts), GenerationMode = JsonSourceGenerationMode.Serialization)] internal sealed partial class JsonContext : JsonSerializerContext { } diff --git a/src/NATS.Client.Core/Internal/SslStreamConnection.cs b/src/NATS.Client.Core/Internal/SslStreamConnection.cs index 9a17b1d8f..b4ab8e0bf 100644 --- a/src/NATS.Client.Core/Internal/SslStreamConnection.cs +++ b/src/NATS.Client.Core/Internal/SslStreamConnection.cs @@ -9,15 +9,15 @@ internal sealed class SslStreamConnection : ISocketConnection { private readonly SslStream _sslStream; private readonly TaskCompletionSource _waitForClosedSource; - private readonly TlsOptions _tlsOptions; + private readonly NatsTlsOpts _tlsOpts; private readonly TlsCerts? _tlsCerts; private readonly CancellationTokenSource _closeCts = new(); private int _disposed; - public SslStreamConnection(SslStream sslStream, TlsOptions tlsOptions, TlsCerts? tlsCerts, TaskCompletionSource waitForClosedSource) + public SslStreamConnection(SslStream sslStream, NatsTlsOpts tlsOpts, TlsCerts? tlsCerts, TaskCompletionSource waitForClosedSource) { _sslStream = sslStream; - _tlsOptions = tlsOptions; + _tlsOpts = tlsOpts; _tlsCerts = tlsCerts; _waitForClosedSource = waitForClosedSource; } @@ -125,7 +125,7 @@ private bool RcsCbCaCertChain( private SslClientAuthenticationOptions SslClientAuthenticationOptions(string targetHost) { - if (_tlsOptions.Disabled) + if (_tlsOpts.Disabled) { throw new InvalidOperationException("TLS is not permitted when TlsOptions.Disabled is set"); } @@ -137,7 +137,7 @@ private SslClientAuthenticationOptions SslClientAuthenticationOptions(string tar } RemoteCertificateValidationCallback? rcsCb = default; - if (_tlsOptions.InsecureSkipVerify) + if (_tlsOpts.InsecureSkipVerify) { rcsCb = RcsCbInsecureSkipVerify; } diff --git a/src/NATS.Client.Core/Internal/TcpConnection.cs b/src/NATS.Client.Core/Internal/TcpConnection.cs index 1885be1e7..9f372b693 100644 --- a/src/NATS.Client.Core/Internal/TcpConnection.cs +++ b/src/NATS.Client.Core/Internal/TcpConnection.cs @@ -120,13 +120,13 @@ public void SignalDisconnected(Exception exception) // NetworkStream will own the Socket, so mark as disposed // in order to skip socket.Dispose() in DisposeAsync - public SslStreamConnection UpgradeToSslStreamConnection(TlsOptions tlsOptions, TlsCerts? tlsCerts) + public SslStreamConnection UpgradeToSslStreamConnection(NatsTlsOpts tlsOpts, TlsCerts? tlsCerts) { if (Interlocked.Increment(ref _disposed) == 1) { return new SslStreamConnection( new SslStream(new NetworkStream(_socket, true)), - tlsOptions, + tlsOpts, tlsCerts, _waitForClosedSource); } diff --git a/src/NATS.Client.Core/Internal/TlsCerts.cs b/src/NATS.Client.Core/Internal/TlsCerts.cs index 336d74b35..b9024c249 100644 --- a/src/NATS.Client.Core/Internal/TlsCerts.cs +++ b/src/NATS.Client.Core/Internal/TlsCerts.cs @@ -4,28 +4,28 @@ namespace NATS.Client.Core.Internal; internal class TlsCerts { - public TlsCerts(TlsOptions tlsOptions) + public TlsCerts(NatsTlsOpts tlsOpts) { - if (tlsOptions.Disabled) + if (tlsOpts.Disabled) { return; } - if ((tlsOptions.CertFile != default && tlsOptions.KeyFile == default) || - (tlsOptions.KeyFile != default && tlsOptions.CertFile == default)) + if ((tlsOpts.CertFile != default && tlsOpts.KeyFile == default) || + (tlsOpts.KeyFile != default && tlsOpts.CertFile == default)) { - throw new ArgumentException("TlsOptions.CertFile and TlsOptions.KeyFile must both be set"); + throw new ArgumentException("NatsTlsOpts.CertFile and NatsTlsOpts.KeyFile must both be set"); } - if (tlsOptions.CaFile != default) + if (tlsOpts.CaFile != default) { CaCerts = new X509Certificate2Collection(); - CaCerts.ImportFromPemFile(tlsOptions.CaFile); + CaCerts.ImportFromPemFile(tlsOpts.CaFile); } - if (tlsOptions.CertFile != default && tlsOptions.KeyFile != default) + if (tlsOpts.CertFile != default && tlsOpts.KeyFile != default) { - ClientCerts = new X509Certificate2Collection(X509Certificate2.CreateFromPemFile(tlsOptions.CertFile, tlsOptions.KeyFile)); + ClientCerts = new X509Certificate2Collection(X509Certificate2.CreateFromPemFile(tlsOpts.CertFile, tlsOpts.KeyFile)); } } diff --git a/src/NATS.Client.Core/Internal/UserCredentials.cs b/src/NATS.Client.Core/Internal/UserCredentials.cs index 73a3f54c1..9827d35f0 100644 --- a/src/NATS.Client.Core/Internal/UserCredentials.cs +++ b/src/NATS.Client.Core/Internal/UserCredentials.cs @@ -5,21 +5,21 @@ namespace NATS.Client.Core.Internal; internal class UserCredentials { - public UserCredentials(NatsAuthOptions authOptions) + public UserCredentials(NatsAuthOpts authOpts) { - Jwt = authOptions.Jwt; - Seed = authOptions.Seed; - Nkey = authOptions.Nkey; - Token = authOptions.Token; + Jwt = authOpts.Jwt; + Seed = authOpts.Seed; + Nkey = authOpts.Nkey; + Token = authOpts.Token; - if (!string.IsNullOrEmpty(authOptions.CredsFile)) + if (!string.IsNullOrEmpty(authOpts.CredsFile)) { - (Jwt, Seed) = LoadCredsFile(authOptions.CredsFile); + (Jwt, Seed) = LoadCredsFile(authOpts.CredsFile); } - if (!string.IsNullOrEmpty(authOptions.NKeyFile)) + if (!string.IsNullOrEmpty(authOpts.NKeyFile)) { - (Seed, Nkey) = LoadNKeyFile(authOptions.NKeyFile); + (Seed, Nkey) = LoadNKeyFile(authOpts.NKeyFile); } } @@ -43,12 +43,12 @@ public UserCredentials(NatsAuthOptions authOptions) return sig; } - internal void Authenticate(ClientOptions options, ServerInfo? info) + internal void Authenticate(ClientOpts opts, ServerInfo? info) { - options.JWT = Jwt; - options.Nkey = Nkey; - options.AuthToken = Token; - options.Sig = info is { AuthRequired: true, Nonce: { } } ? Sign(info.Nonce) : null; + opts.JWT = Jwt; + opts.Nkey = Nkey; + opts.AuthToken = Token; + opts.Sig = info is { AuthRequired: true, Nonce: { } } ? Sign(info.Nonce) : null; } private (string, string) LoadCredsFile(string path) diff --git a/src/NATS.Client.Core/NatsAuthOptions.cs b/src/NATS.Client.Core/NatsAuthOpts.cs similarity index 90% rename from src/NATS.Client.Core/NatsAuthOptions.cs rename to src/NATS.Client.Core/NatsAuthOpts.cs index d7f91e59a..ab2fc3700 100644 --- a/src/NATS.Client.Core/NatsAuthOptions.cs +++ b/src/NATS.Client.Core/NatsAuthOpts.cs @@ -1,8 +1,8 @@ namespace NATS.Client.Core; -public record NatsAuthOptions +public record NatsAuthOpts { - public static readonly NatsAuthOptions Default = new(); + public static readonly NatsAuthOpts Default = new(); public string? Username { get; init; } diff --git a/src/NATS.Client.Core/NatsConnection.RequestReply.cs b/src/NATS.Client.Core/NatsConnection.RequestReply.cs index b54c8a113..12ac3b7bc 100644 --- a/src/NATS.Client.Core/NatsConnection.RequestReply.cs +++ b/src/NATS.Client.Core/NatsConnection.RequestReply.cs @@ -1,4 +1,4 @@ -using System.Buffers; +using System.Buffers; using System.Runtime.CompilerServices; namespace NATS.Client.Core; diff --git a/src/NATS.Client.Core/NatsConnection.cs b/src/NATS.Client.Core/NatsConnection.cs index 88a9220d7..12b8af449 100644 --- a/src/NATS.Client.Core/NatsConnection.cs +++ b/src/NATS.Client.Core/NatsConnection.cs @@ -48,7 +48,7 @@ public partial class NatsConnection : IAsyncDisposable, INatsConnection private NatsPipeliningWriteProtocolProcessor? _socketWriter; private TaskCompletionSource _waitForOpenConnection; private TlsCerts? _tlsCerts; - private ClientOptions _clientOptions; + private ClientOpts _clientOpts; private UserCredentials? _userCredentials; public NatsConnection() @@ -71,7 +71,7 @@ public NatsConnection(NatsOpts opts) InboxPrefix = $"{opts.InboxPrefix}.{Guid.NewGuid():n}."; SubscriptionManager = new SubscriptionManager(this, InboxPrefix); _logger = opts.LoggerFactory.CreateLogger(); - _clientOptions = ClientOptions.Create(Opts); + _clientOpts = ClientOpts.Create(Opts); HeaderParser = new HeaderParser(opts.HeaderEncoding); } @@ -222,14 +222,14 @@ private async ValueTask InitialConnectAsync() Debug.Assert(ConnectionState == NatsConnectionState.Connecting, "Connection state"); var uris = Opts.GetSeedUris(); - if (Opts.TlsOptions.Disabled && uris.Any(u => u.IsTls)) - throw new NatsException($"URI {uris.First(u => u.IsTls)} requires TLS but TlsOptions.Disabled is set to true"); - if (Opts.TlsOptions.Required) - _tlsCerts = new TlsCerts(Opts.TlsOptions); + if (Opts.TlsOpts.Disabled && uris.Any(u => u.IsTls)) + throw new NatsException($"URI {uris.First(u => u.IsTls)} requires TLS but NatsTlsOpts.Disabled is set to true"); + if (Opts.TlsOpts.Required) + _tlsCerts = new TlsCerts(Opts.TlsOpts); - if (!Opts.AuthOptions.IsAnonymous) + if (!Opts.AuthOpts.IsAnonymous) { - _userCredentials = new UserCredentials(Opts.AuthOptions); + _userCredentials = new UserCredentials(Opts.AuthOpts); } foreach (var uri in uris) @@ -331,19 +331,19 @@ private async ValueTask SetupReaderWriterAsync(bool reconnect) // check to see if we should upgrade to TLS if (_socket is TcpConnection tcpConnection) { - if (Opts.TlsOptions.Disabled && WritableServerInfo!.TlsRequired) + if (Opts.TlsOpts.Disabled && WritableServerInfo!.TlsRequired) { throw new NatsException( - $"Server {_currentConnectUri} requires TLS but TlsOptions.Disabled is set to true"); + $"Server {_currentConnectUri} requires TLS but NatsTlsOpts.Disabled is set to true"); } - if (Opts.TlsOptions.Required && !WritableServerInfo!.TlsRequired && !WritableServerInfo.TlsAvailable) + if (Opts.TlsOpts.Required && !WritableServerInfo!.TlsRequired && !WritableServerInfo.TlsAvailable) { throw new NatsException( - $"Server {_currentConnectUri} does not support TLS but TlsOptions.Disabled is set to true"); + $"Server {_currentConnectUri} does not support TLS but NatsTlsOpts.Disabled is set to true"); } - if (Opts.TlsOptions.Required || WritableServerInfo!.TlsRequired || WritableServerInfo.TlsAvailable) + if (Opts.TlsOpts.Required || WritableServerInfo!.TlsRequired || WritableServerInfo.TlsAvailable) { // do TLS upgrade // if the current URI is not a seed URI and is not a DNS hostname, check the server cert against the @@ -364,7 +364,7 @@ private async ValueTask SetupReaderWriterAsync(bool reconnect) _socketReader = null; // upgrade TcpConnection to SslConnection - var sslConnection = tcpConnection.UpgradeToSslStreamConnection(Opts.TlsOptions, _tlsCerts); + var sslConnection = tcpConnection.UpgradeToSslStreamConnection(Opts.TlsOpts, _tlsCerts); await sslConnection.AuthenticateAsClientAsync(targetHost).ConfigureAwait(false); _socket = sslConnection; @@ -379,11 +379,11 @@ private async ValueTask SetupReaderWriterAsync(bool reconnect) infoParsedSignal.SetResult(); // Authentication - _userCredentials?.Authenticate(_clientOptions, WritableServerInfo); + _userCredentials?.Authenticate(_clientOpts, WritableServerInfo); // add CONNECT and PING command to priority lane _writerState.PriorityCommands.Clear(); - var connectCommand = AsyncConnectCommand.Create(_pool, _clientOptions, GetCancellationTimer(CancellationToken.None)); + var connectCommand = AsyncConnectCommand.Create(_pool, _clientOpts, GetCancellationTimer(CancellationToken.None)); _writerState.PriorityCommands.Add(connectCommand); _writerState.PriorityCommands.Add(PingCommand.Create(_pool, GetCancellationTimer(CancellationToken.None))); diff --git a/src/NATS.Client.Core/NatsOpts.cs b/src/NATS.Client.Core/NatsOpts.cs index d461a8ae3..7923a8bc2 100644 --- a/src/NATS.Client.Core/NatsOpts.cs +++ b/src/NATS.Client.Core/NatsOpts.cs @@ -13,8 +13,8 @@ namespace NATS.Client.Core; /// /// /// -/// -/// +/// +/// /// /// /// @@ -41,8 +41,8 @@ public sealed record NatsOpts bool Echo, bool Verbose, bool Headers, - NatsAuthOptions AuthOptions, - TlsOptions TlsOptions, + NatsAuthOpts AuthOpts, + NatsTlsOpts TlsOpts, INatsSerializer Serializer, ILoggerFactory LoggerFactory, int WriterBufferSize, @@ -69,8 +69,8 @@ public sealed record NatsOpts Echo: true, Verbose: false, Headers: true, - AuthOptions: NatsAuthOptions.Default, - TlsOptions: TlsOptions.Default, + AuthOpts: NatsAuthOpts.Default, + TlsOpts: NatsTlsOpts.Default, Serializer: JsonNatsSerializer.Default, LoggerFactory: NullLoggerFactory.Instance, WriterBufferSize: 65534, // 32767 diff --git a/src/NATS.Client.Core/NatsRequestExtensions.cs b/src/NATS.Client.Core/NatsRequestExtensions.cs index d2482e249..64d6387bf 100644 --- a/src/NATS.Client.Core/NatsRequestExtensions.cs +++ b/src/NATS.Client.Core/NatsRequestExtensions.cs @@ -18,7 +18,7 @@ public static class NatsRequestExtensions /// /// Response can be (null) or one . /// Reply option's max messages will be set to 1. - /// if reply option's timeout is not defined then it will be set to NatsOptions.RequestTimeout. + /// if reply option's timeout is not defined then it will be set to NatsOpts.RequestTimeout. /// public static ValueTask?> RequestAsync( this INatsConnection nats, @@ -47,7 +47,7 @@ public static class NatsRequestExtensions /// /// Response can be (null) or one . /// Reply option's max messages will be set to 1. - /// if reply option's timeout is not defined then it will be set to NatsOptions.RequestTimeout. + /// if reply option's timeout is not defined then it will be set to NatsOpts.RequestTimeout. /// public static ValueTask RequestAsync( this INatsConnection nats, diff --git a/src/NATS.Client.Core/NatsRequestManyExtensions.cs b/src/NATS.Client.Core/NatsRequestManyExtensions.cs index 889f53d8e..bee9b6aba 100644 --- a/src/NATS.Client.Core/NatsRequestManyExtensions.cs +++ b/src/NATS.Client.Core/NatsRequestManyExtensions.cs @@ -14,7 +14,7 @@ public static class NatsRequestManyExtensions /// An asynchronous enumerable of objects /// Raised when cancellation token is used /// - /// if reply option's timeout is not defined then it will be set to NatsOptions.RequestTimeout. + /// if reply option's timeout is not defined then it will be set to NatsOpts.RequestTimeout. /// public static IAsyncEnumerable RequestManyAsync( this INatsConnection nats, @@ -43,7 +43,7 @@ public static IAsyncEnumerable RequestManyAsync( /// An asynchronous enumerable of objects /// Raised when cancellation token is used /// - /// if reply option's timeout is not defined then it will be set to NatsOptions.RequestTimeout. + /// if reply option's timeout is not defined then it will be set to NatsOpts.RequestTimeout. /// public static IAsyncEnumerable> RequestManyAsync( this INatsConnection nats, diff --git a/src/NATS.Client.Core/NatsSub.cs b/src/NATS.Client.Core/NatsSub.cs index 1f606d83a..f25067367 100644 --- a/src/NATS.Client.Core/NatsSub.cs +++ b/src/NATS.Client.Core/NatsSub.cs @@ -7,7 +7,7 @@ namespace NATS.Client.Core; public sealed class NatsSub : NatsSubBase, INatsSub { - private static readonly BoundedChannelOptions DefaultChannelOptions = + private static readonly BoundedChannelOptions DefaultChannelOpts = new BoundedChannelOptions(1_000) { FullMode = BoundedChannelFullMode.Wait, @@ -21,30 +21,30 @@ public sealed class NatsSub : NatsSubBase, INatsSub internal NatsSub(NatsConnection connection, ISubscriptionManager manager, string subject, NatsSubOpts? opts) : base(connection, manager, subject, opts) => _msgs = Channel.CreateBounded( - GetChannelOptions(opts?.ChannelOptions)); + GetChannelOpts(opts?.ChannelOpts)); public ChannelReader Msgs => _msgs.Reader; - internal static BoundedChannelOptions GetChannelOptions( + internal static BoundedChannelOptions GetChannelOpts( NatsSubChannelOpts? subChannelOpts) { if (subChannelOpts != null) { var overrideOpts = subChannelOpts.Value; return new BoundedChannelOptions(overrideOpts.Capacity ?? - DefaultChannelOptions.Capacity) + DefaultChannelOpts.Capacity) { AllowSynchronousContinuations = - DefaultChannelOptions.AllowSynchronousContinuations, + DefaultChannelOpts.AllowSynchronousContinuations, FullMode = - overrideOpts.FullMode ?? DefaultChannelOptions.FullMode, - SingleWriter = DefaultChannelOptions.SingleWriter, - SingleReader = DefaultChannelOptions.SingleReader, + overrideOpts.FullMode ?? DefaultChannelOpts.FullMode, + SingleWriter = DefaultChannelOpts.SingleWriter, + SingleReader = DefaultChannelOpts.SingleReader, }; } else { - return DefaultChannelOptions; + return DefaultChannelOpts; } } @@ -79,7 +79,7 @@ internal NatsSub( : base(connection, manager, subject, opts) { _msgs = Channel.CreateBounded>( - NatsSub.GetChannelOptions(opts?.ChannelOptions)); + NatsSub.GetChannelOpts(opts?.ChannelOpts)); Serializer = serializer; } diff --git a/src/NATS.Client.Core/NatsSubOpts.cs b/src/NATS.Client.Core/NatsSubOpts.cs index e4f3321bb..2cae34fd2 100644 --- a/src/NATS.Client.Core/NatsSubOpts.cs +++ b/src/NATS.Client.Core/NatsSubOpts.cs @@ -64,5 +64,5 @@ public readonly record struct NatsSubOpts /// /// Allows Configuration of options for a subscription. /// - public NatsSubChannelOpts? ChannelOptions { get; init; } + public NatsSubChannelOpts? ChannelOpts { get; init; } } diff --git a/src/NATS.Client.Core/TlsOptions.cs b/src/NATS.Client.Core/NatsTlsOpts.cs similarity index 90% rename from src/NATS.Client.Core/TlsOptions.cs rename to src/NATS.Client.Core/NatsTlsOpts.cs index 1c8da180f..f23a9fc18 100644 --- a/src/NATS.Client.Core/TlsOptions.cs +++ b/src/NATS.Client.Core/NatsTlsOpts.cs @@ -4,9 +4,9 @@ namespace NATS.Client.Core; /// Immutable options for TlsOptions, you can configure via `with` operator. /// These options are ignored in WebSocket connections /// -public sealed record TlsOptions +public sealed record NatsTlsOpts { - public static readonly TlsOptions Default = new(); + public static readonly NatsTlsOpts Default = new(); /// Path to PEM-encoded X509 Certificate public string? CertFile { get; init; } diff --git a/src/NATS.Client.Hosting/NatsHostingExtensions.cs b/src/NATS.Client.Hosting/NatsHostingExtensions.cs index 2d0205b39..eb3ab21aa 100644 --- a/src/NATS.Client.Hosting/NatsHostingExtensions.cs +++ b/src/NATS.Client.Hosting/NatsHostingExtensions.cs @@ -11,7 +11,7 @@ public static class NatsHostingExtensions /// Add NatsConnection/Pool to ServiceCollection. When poolSize = 1, registered `NatsConnection` and `INatsCommand` as singleton. /// Others, registered `NatsConnectionPool` as singleton, `NatsConnection` and `INatsCommand` as transient(get from pool). /// - public static IServiceCollection AddNats(this IServiceCollection services, int poolSize = 1, Func? configureOptions = null, Action? configureConnection = null) + public static IServiceCollection AddNats(this IServiceCollection services, int poolSize = 1, Func? configureOpts = null, Action? configureConnection = null) { poolSize = Math.Max(poolSize, 1); @@ -20,9 +20,9 @@ public static IServiceCollection AddNats(this IServiceCollection services, int p services.TryAddSingleton(provider => { var options = NatsOpts.Default with { LoggerFactory = provider.GetRequiredService() }; - if (configureOptions != null) + if (configureOpts != null) { - options = configureOptions(options); + options = configureOpts(options); } return new NatsConnectionPool(poolSize, options, configureConnection ?? (_ => { })); @@ -49,9 +49,9 @@ public static IServiceCollection AddNats(this IServiceCollection services, int p services.TryAddSingleton(provider => { var options = NatsOpts.Default with { LoggerFactory = provider.GetRequiredService() }; - if (configureOptions != null) + if (configureOpts != null) { - options = configureOptions(options); + options = configureOpts(options); } var conn = new NatsConnection(options); diff --git a/src/NATS.Client.JetStream/Internal/NatsJSExtensionsInternal.cs b/src/NATS.Client.JetStream/Internal/NatsJSExtensionsInternal.cs index 9554afa6c..c03345f9d 100644 --- a/src/NATS.Client.JetStream/Internal/NatsJSExtensionsInternal.cs +++ b/src/NATS.Client.JetStream/Internal/NatsJSExtensionsInternal.cs @@ -1,4 +1,4 @@ -namespace NATS.Client.JetStream.Internal; +namespace NATS.Client.JetStream.Internal; public static class NatsJSExtensionsInternal { diff --git a/src/NATS.Client.JetStream/NatsJSConsumer.cs b/src/NATS.Client.JetStream/NatsJSConsumer.cs index b030cc3c3..0178d3991 100644 --- a/src/NATS.Client.JetStream/NatsJSConsumer.cs +++ b/src/NATS.Client.JetStream/NatsJSConsumer.cs @@ -52,7 +52,7 @@ public async ValueTask> ConsumeAsync(NatsJSConsumeOpts o var requestOpts = new NatsSubOpts { Serializer = opts.Serializer, - ChannelOptions = new NatsSubChannelOpts + ChannelOpts = new NatsSubChannelOpts { // Keep capacity at 1 to make sure message acknowledgements are sent // right after the message is processed and messages aren't queued up @@ -144,7 +144,7 @@ public async ValueTask> FetchAsync( var requestOpts = new NatsSubOpts { Serializer = opts.Serializer, - ChannelOptions = new NatsSubChannelOpts + ChannelOpts = new NatsSubChannelOpts { // Keep capacity at 1 to make sure message acknowledgements are sent // right after the message is processed and messages aren't queued up diff --git a/src/NATS.Client.JetStream/NatsJSContext.cs b/src/NATS.Client.JetStream/NatsJSContext.cs index ce53d3952..cf0b57db2 100644 --- a/src/NATS.Client.JetStream/NatsJSContext.cs +++ b/src/NATS.Client.JetStream/NatsJSContext.cs @@ -22,8 +22,6 @@ public NatsJSContext(NatsConnection connection, NatsJSOpts opts) internal NatsJSOpts Opts { get; } - internal string NewInbox() => $"{Opts.InboxPrefix}.{Guid.NewGuid():n}"; - public ValueTask GetAccountInfoAsync(CancellationToken cancellationToken = default) => JSRequestResponseAsync( subject: $"{Opts.ApiPrefix}.INFO", @@ -60,6 +58,8 @@ public async ValueTask PublishAsync( throw new NatsJSException("No response received"); } + internal string NewInbox() => $"{Opts.InboxPrefix}.{Guid.NewGuid():n}"; + internal async ValueTask JSRequestResponseAsync( string subject, TRequest? request, diff --git a/src/NATS.Client.JetStream/NatsJSOpts.cs b/src/NATS.Client.JetStream/NatsJSOpts.cs index 07362c28b..a48816c52 100644 --- a/src/NATS.Client.JetStream/NatsJSOpts.cs +++ b/src/NATS.Client.JetStream/NatsJSOpts.cs @@ -20,7 +20,7 @@ public NatsJSOpts(NatsOpts opts, string? apiPrefix = default, int? maxMsgs = def /// /// Prefix to use in inbox subscription subjects to receive messages from JetStream. (default: _INBOX) /// - /// Default is taken from NatsOptions (on the parent NatsConnection) which is '_INBOX' if not set. + /// Default is taken from NatsOpts (on the parent NatsConnection) which is '_INBOX' if not set. /// /// public string InboxPrefix { get; init; } diff --git a/src/NATS.Client.JetStream/NatsJSSubConsume.cs b/src/NATS.Client.JetStream/NatsJSSubConsume.cs index 0a4213d47..6c6e8fc92 100644 --- a/src/NATS.Client.JetStream/NatsJSSubConsume.cs +++ b/src/NATS.Client.JetStream/NatsJSSubConsume.cs @@ -1,4 +1,4 @@ -using System.Buffers; +using System.Buffers; using System.Text; using System.Threading.Channels; using Microsoft.Extensions.Logging; @@ -95,13 +95,13 @@ public NatsJSSubConsume( Timeout.Infinite, Timeout.Infinite); - _userMsgs = Channel.CreateBounded>(NatsSub.GetChannelOptions(opts?.ChannelOptions)); + _userMsgs = Channel.CreateBounded>(NatsSub.GetChannelOpts(opts?.ChannelOpts)); Msgs = _userMsgs.Reader; - _pullRequests = Channel.CreateBounded(NatsSub.GetChannelOptions(opts?.ChannelOptions)); + _pullRequests = Channel.CreateBounded(NatsSub.GetChannelOpts(opts?.ChannelOpts)); _pullTask = Task.Run(PullLoop); - _notifications = Channel.CreateBounded(NatsSub.GetChannelOptions(opts?.ChannelOptions)); + _notifications = Channel.CreateBounded(NatsSub.GetChannelOpts(opts?.ChannelOpts)); _notificationsTask = Task.Run(NotificationsLoop); } diff --git a/src/NATS.Client.JetStream/NatsJSSubFetch.cs b/src/NATS.Client.JetStream/NatsJSSubFetch.cs index 55d46a890..9db8545b9 100644 --- a/src/NATS.Client.JetStream/NatsJSSubFetch.cs +++ b/src/NATS.Client.JetStream/NatsJSSubFetch.cs @@ -1,4 +1,4 @@ -using System.Buffers; +using System.Buffers; using System.Text; using System.Threading.Channels; using Microsoft.Extensions.Logging; @@ -60,10 +60,10 @@ public NatsJSSubFetch( _pendingMsgs = _maxMsgs; _pendingBytes = _maxBytes; - _userMsgs = Channel.CreateBounded>(NatsSub.GetChannelOptions(opts?.ChannelOptions)); + _userMsgs = Channel.CreateBounded>(NatsSub.GetChannelOpts(opts?.ChannelOpts)); Msgs = _userMsgs.Reader; - _notifications = Channel.CreateBounded(NatsSub.GetChannelOptions(opts?.ChannelOptions)); + _notifications = Channel.CreateBounded(NatsSub.GetChannelOpts(opts?.ChannelOpts)); _notificationsTask = Task.Run(NotificationsLoop); _hbTimer = new Timer( @@ -136,70 +136,70 @@ protected override async ValueTask ReceiveInternalAsync( ReadOnlySequence? headersBuffer, ReadOnlySequence payloadBuffer) { - ResetHeartbeatTimer(); - if (subject == Subject) + ResetHeartbeatTimer(); + if (subject == Subject) + { + if (headersBuffer.HasValue) { - if (headersBuffer.HasValue) + var headers = new NatsHeaders(); + if (Connection.HeaderParser.ParseHeaders(new SequenceReader(headersBuffer.Value), headers)) { - var headers = new NatsHeaders(); - if (Connection.HeaderParser.ParseHeaders(new SequenceReader(headersBuffer.Value), headers)) + if (headers is { Code: 408, Message: NatsHeaders.Messages.RequestTimeout }) + { + EndSubscription(NatsSubEndReason.Timeout); + } + else if (headers is { Code: 409, Message: NatsHeaders.Messages.MessageSizeExceedsMaxBytes }) + { + EndSubscription(NatsSubEndReason.MaxBytes); + } + else if (headers is { Code: 100, Message: NatsHeaders.Messages.IdleHeartbeat }) { - if (headers is { Code: 408, Message: NatsHeaders.Messages.RequestTimeout }) - { - EndSubscription(NatsSubEndReason.Timeout); - } - else if (headers is { Code: 409, Message: NatsHeaders.Messages.MessageSizeExceedsMaxBytes }) - { - EndSubscription(NatsSubEndReason.MaxBytes); - } - else if (headers is { Code: 100, Message: NatsHeaders.Messages.IdleHeartbeat }) - { - } - else - { - _notifications.Writer.TryWrite(new NatsJSNotification(headers.Code, headers.MessageText)); - } } else { - _logger.LogError( - "Can't parse headers: {HeadersBuffer}", - Encoding.ASCII.GetString(headersBuffer.Value.ToArray())); - throw new NatsJSException("Can't parse headers"); + _notifications.Writer.TryWrite(new NatsJSNotification(headers.Code, headers.MessageText)); } } else { - throw new NatsJSException("No header found"); + _logger.LogError( + "Can't parse headers: {HeadersBuffer}", + Encoding.ASCII.GetString(headersBuffer.Value.ToArray())); + throw new NatsJSException("Can't parse headers"); } } else { - var msg = new NatsJSMsg( - NatsMsg.Build( - subject, - replyTo, - headersBuffer, - payloadBuffer, - Connection, - Connection.HeaderParser, - _serializer), - _context); - - _pendingMsgs--; - _pendingBytes -= msg.Size; - - await _userMsgs.Writer.WriteAsync(msg).ConfigureAwait(false); + throw new NatsJSException("No header found"); } + } + else + { + var msg = new NatsJSMsg( + NatsMsg.Build( + subject, + replyTo, + headersBuffer, + payloadBuffer, + Connection, + Connection.HeaderParser, + _serializer), + _context); + + _pendingMsgs--; + _pendingBytes -= msg.Size; + + await _userMsgs.Writer.WriteAsync(msg).ConfigureAwait(false); + } - if (_maxBytes > 0 && _pendingBytes <= 0) - { - EndSubscription(NatsSubEndReason.MaxBytes); - } - else if (_maxBytes == 0 && _pendingMsgs == 0) - { - EndSubscription(NatsSubEndReason.MaxMsgs); - } + if (_maxBytes > 0 && _pendingBytes <= 0) + { + EndSubscription(NatsSubEndReason.MaxBytes); + } + else if (_maxBytes == 0 && _pendingMsgs == 0) + { + EndSubscription(NatsSubEndReason.MaxMsgs); + } } protected override void TryComplete() diff --git a/tests/NATS.Client.Core.Tests/NatsConnectionTest.Auth.cs b/tests/NATS.Client.Core.Tests/NatsConnectionTest.Auth.cs index 795aa2d00..c7f33ca89 100644 --- a/tests/NATS.Client.Core.Tests/NatsConnectionTest.Auth.cs +++ b/tests/NATS.Client.Core.Tests/NatsConnectionTest.Auth.cs @@ -9,7 +9,7 @@ public static IEnumerable GetAuthConfigs() new Auth( "TOKEN", "resources/configs/auth/token.conf", - NatsOpts.Default with { AuthOptions = NatsAuthOptions.Default with { Token = "s3cr3t", }, }), + NatsOpts.Default with { AuthOpts = NatsAuthOpts.Default with { Token = "s3cr3t", }, }), }; yield return new object[] @@ -19,7 +19,7 @@ public static IEnumerable GetAuthConfigs() "resources/configs/auth/password.conf", NatsOpts.Default with { - AuthOptions = NatsAuthOptions.Default with { Username = "a", Password = "b", }, + AuthOpts = NatsAuthOpts.Default with { Username = "a", Password = "b", }, }), }; @@ -30,7 +30,7 @@ NatsOpts.Default with "resources/configs/auth/nkey.conf", NatsOpts.Default with { - AuthOptions = NatsAuthOptions.Default with + AuthOpts = NatsAuthOpts.Default with { Nkey = "UALQSMXRSAA7ZXIGDDJBJ2JOYJVQIWM3LQVDM5KYIPG4EP3FAGJ47BOJ", Seed = "SUAAVWRZG6M5FA5VRRGWSCIHKTOJC7EWNIT4JV3FTOIPO4OBFR5WA7X5TE", @@ -45,7 +45,7 @@ NatsOpts.Default with "resources/configs/auth/nkey.conf", NatsOpts.Default with { - AuthOptions = NatsAuthOptions.Default with { NKeyFile = "resources/configs/auth/user.nk", }, + AuthOpts = NatsAuthOpts.Default with { NKeyFile = "resources/configs/auth/user.nk", }, }), }; @@ -56,7 +56,7 @@ NatsOpts.Default with "resources/configs/auth/operator.conf", NatsOpts.Default with { - AuthOptions = NatsAuthOptions.Default with + AuthOpts = NatsAuthOpts.Default with { Jwt = "eyJ0eXAiOiJKV1QiLCJhbGciOiJlZDI1NTE5LW5rZXkifQ.eyJqdGkiOiJOVDJTRkVIN0pNSUpUTzZIQ09GNUpYRFNDUU1WRlFNV0MyWjI1TFk3QVNPTklYTjZFVlhBIiwiaWF0IjoxNjc5MTQ0MDkwLCJpc3MiOiJBREpOSlpZNUNXQlI0M0NOSzJBMjJBMkxPSkVBSzJSS1RaTk9aVE1HUEVCRk9QVE5FVFBZTUlLNSIsIm5hbWUiOiJteS11c2VyIiwic3ViIjoiVUJPWjVMUVJPTEpRRFBBQUNYSk1VRkJaS0Q0R0JaSERUTFo3TjVQS1dSWFc1S1dKM0VBMlc0UloiLCJuYXRzIjp7InB1YiI6e30sInN1YiI6e30sInN1YnMiOi0xLCJkYXRhIjotMSwicGF5bG9hZCI6LTEsInR5cGUiOiJ1c2VyIiwidmVyc2lvbiI6Mn19.ElYEknDixe9pZdl55S9PjduQhhqR1OQLglI1JO7YK7ECYb1mLUjGd8ntcR7ISS04-_yhygSDzX8OS8buBIxMDA", @@ -72,7 +72,7 @@ NatsOpts.Default with "resources/configs/auth/operator.conf", NatsOpts.Default with { - AuthOptions = NatsAuthOptions.Default with { CredsFile = "resources/configs/auth/user.creds", }, + AuthOpts = NatsAuthOpts.Default with { CredsFile = "resources/configs/auth/user.creds", }, }), }; } @@ -83,16 +83,16 @@ public async Task UserCredentialAuthTest(Auth auth) { var name = auth.Name; var serverConfig = auth.ServerConfig; - var clientOptions = auth.ClientOpts; + var clientOpts = auth.ClientOpts; _output.WriteLine($"AUTH TEST {name}"); - var serverOptions = new NatsServerOptionsBuilder() + var serverOpts = new NatsServerOptsBuilder() .UseTransport(_transportType) .AddServerConfig(serverConfig) .Build(); - await using var server = NatsServer.Start(_output, serverOptions, clientOptions); + await using var server = NatsServer.Start(_output, serverOpts, clientOpts); var subject = Guid.NewGuid().ToString("N"); @@ -104,8 +104,8 @@ public async Task UserCredentialAuthTest(Auth auth) Assert.Contains("Authorization Violation", natsException.GetBaseException().Message); } - await using var subConnection = server.CreateClientConnection(clientOptions); - await using var pubConnection = server.CreateClientConnection(clientOptions); + await using var subConnection = server.CreateClientConnection(clientOpts); + await using var pubConnection = server.CreateClientConnection(clientOpts); var signalComplete1 = new WaitSignal(); var signalComplete2 = new WaitSignal(); @@ -141,7 +141,7 @@ await Retry.Until( await disconnectSignal2; _output.WriteLine("START NEW SERVER"); - await using var newServer = NatsServer.Start(_output, serverOptions, clientOptions); + await using var newServer = NatsServer.Start(_output, serverOpts, clientOpts); await subConnection.ConnectAsync(); // wait open again await pubConnection.ConnectAsync(); // wait open again diff --git a/tests/NATS.Client.Core.Tests/NatsConnectionTest.cs b/tests/NATS.Client.Core.Tests/NatsConnectionTest.cs index 8e361b07c..06a82d067 100644 --- a/tests/NATS.Client.Core.Tests/NatsConnectionTest.cs +++ b/tests/NATS.Client.Core.Tests/NatsConnectionTest.cs @@ -150,7 +150,7 @@ await Retry.Until( [Fact] public async Task ReconnectSingleTest() { - using var options = new NatsServerOptions + using var options = new NatsServerOpts { TransportType = _transportType, EnableWebSocket = _transportType == TransportType.WebSocket, @@ -298,7 +298,7 @@ await Retry.Until( var disconnectSignal = connection1.ConnectionDisconnectedAsAwaitable(); // register disconnect before kill - _output.WriteLine($"TRY KILL SERVER1 Port:{cluster.Server1.Options.ServerPort}"); + _output.WriteLine($"TRY KILL SERVER1 Port:{cluster.Server1.Opts.ServerPort}"); await cluster.Server1.DisposeAsync(); // process kill await disconnectSignal; diff --git a/tests/NATS.Client.Core.Tests/ProtocolTest.cs b/tests/NATS.Client.Core.Tests/ProtocolTest.cs index dc194ca6a..60b6f41b9 100644 --- a/tests/NATS.Client.Core.Tests/ProtocolTest.cs +++ b/tests/NATS.Client.Core.Tests/ProtocolTest.cs @@ -108,7 +108,7 @@ void Log(string text) _output.WriteLine($"[TESTS] {DateTime.Now:HH:mm:ss.fff} {text}"); } - await using var server = NatsServer.Start(_output, new NatsServerOptionsBuilder().UseTransport(TransportType.Tcp).Trace().Build()); + await using var server = NatsServer.Start(_output, new NatsServerOptsBuilder().UseTransport(TransportType.Tcp).Trace().Build()); var (nats, proxy) = server.CreateProxiedClientConnection(); var sync = 0; @@ -175,7 +175,7 @@ void Log(string text) } // Use a single server to test multiple scenarios to make test runs more efficient - await using var server = NatsServer.Start(_output, new NatsServerOptionsBuilder().UseTransport(TransportType.Tcp).Trace().Build()); + await using var server = NatsServer.Start(_output, new NatsServerOptsBuilder().UseTransport(TransportType.Tcp).Trace().Build()); var (nats, proxy) = server.CreateProxiedClientConnection(); var sid = 0; diff --git a/tests/NATS.Client.Core.Tests/SubscriptionTest.cs b/tests/NATS.Client.Core.Tests/SubscriptionTest.cs index dcc3f3a34..9e40e5ce8 100644 --- a/tests/NATS.Client.Core.Tests/SubscriptionTest.cs +++ b/tests/NATS.Client.Core.Tests/SubscriptionTest.cs @@ -9,7 +9,7 @@ public class SubscriptionTest [Fact] public async Task Subscription_periodic_cleanup_test() { - var serverOptions = new NatsServerOptionsBuilder() + var serverOptions = new NatsServerOptsBuilder() .Trace() .UseTransport(TransportType.Tcp) .Build(); diff --git a/tests/NATS.Client.JetStream.Tests/ConsumerConsumeTest.cs b/tests/NATS.Client.JetStream.Tests/ConsumerConsumeTest.cs index dd65373cd..2e0446141 100644 --- a/tests/NATS.Client.JetStream.Tests/ConsumerConsumeTest.cs +++ b/tests/NATS.Client.JetStream.Tests/ConsumerConsumeTest.cs @@ -15,7 +15,7 @@ public async Task Consume_msgs_test() await using var server = NatsServer.Start( outputHelper: _output, - options: new NatsServerOptionsBuilder() + opts: new NatsServerOptsBuilder() .UseTransport(TransportType.Tcp) .Trace() .UseJetStream() @@ -80,7 +80,7 @@ public async Task Consume_idle_heartbeat_test() var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30)); await using var server = NatsServer.Start( outputHelper: new NullOutputHelper(), - options: new NatsServerOptionsBuilder() + opts: new NatsServerOptsBuilder() .UseTransport(TransportType.Tcp) .UseJetStream() .Build()); diff --git a/tests/NATS.Client.JetStream.Tests/JetStreamTest.cs b/tests/NATS.Client.JetStream.Tests/JetStreamTest.cs index 978faff65..f53558fe6 100644 --- a/tests/NATS.Client.JetStream.Tests/JetStreamTest.cs +++ b/tests/NATS.Client.JetStream.Tests/JetStreamTest.cs @@ -14,7 +14,7 @@ public async Task Create_stream_test() { await using var server = NatsServer.Start( outputHelper: _output, - options: new NatsServerOptionsBuilder() + opts: new NatsServerOptsBuilder() .UseTransport(TransportType.Tcp) .Trace() .UseJetStream() diff --git a/tests/NATS.Client.TestUtilities/NatsServer.cs b/tests/NATS.Client.TestUtilities/NatsServer.cs index 310090acf..65124ae76 100644 --- a/tests/NATS.Client.TestUtilities/NatsServer.cs +++ b/tests/NATS.Client.TestUtilities/NatsServer.cs @@ -52,21 +52,21 @@ static NatsServer() Version = new Version(value); } - private NatsServer(ITestOutputHelper outputHelper, NatsServerOptions options) + private NatsServer(ITestOutputHelper outputHelper, NatsServerOpts opts) { _outputHelper = outputHelper; - _transportType = options.TransportType; - Options = options; + _transportType = opts.TransportType; + Opts = opts; - if (options.EnableJetStream) + if (opts.EnableJetStream) { _jetStreamStoreDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("n")); Directory.CreateDirectory(_jetStreamStoreDir); - options.JetStreamStoreDir = _jetStreamStoreDir; + opts.JetStreamStoreDir = _jetStreamStoreDir; } _configFileName = Path.GetTempFileName(); - var config = options.ConfigFileContents; + var config = opts.ConfigFileContents; File.WriteAllText(_configFileName, config); var cmd = $"{NatsServerPath} -c {_configFileName}"; @@ -84,7 +84,7 @@ private NatsServer(ITestOutputHelper outputHelper, NatsServerOptions options) { try { - await client.ConnectAsync("localhost", Options.ServerPort, _cancellationTokenSource.Token); + await client.ConnectAsync("localhost", Opts.ServerPort, _cancellationTokenSource.Token); if (client.Connected) return; } @@ -107,16 +107,16 @@ private NatsServer(ITestOutputHelper outputHelper, NatsServerOptions options) _processErr.GetAwaiter().GetResult(); // throw exception } - outputHelper.WriteLine("OK to Process Start, Port:" + Options.ServerPort); + outputHelper.WriteLine("OK to Process Start, Port:" + Opts.ServerPort); } - public NatsServerOptions Options { get; } + public NatsServerOpts Opts { get; } public string ClientUrl => _transportType switch { - TransportType.Tcp => $"nats://localhost:{Options.ServerPort}", - TransportType.Tls => $"tls://localhost:{Options.ServerPort}", - TransportType.WebSocket => $"ws://localhost:{Options.WebSocketPort}", + TransportType.Tcp => $"nats://localhost:{Opts.ServerPort}", + TransportType.Tls => $"tls://localhost:{Opts.ServerPort}", + TransportType.WebSocket => $"ws://localhost:{Opts.WebSocketPort}", _ => throw new ArgumentOutOfRangeException(), }; @@ -126,11 +126,11 @@ public int ConnectionPort { if (_transportType == TransportType.WebSocket && ServerVersions.V2_9_19 <= Version) { - return Options.WebSocketPort!.Value; + return Opts.WebSocketPort!.Value; } else { - return Options.ServerPort; + return Opts.ServerPort; } } } @@ -139,7 +139,7 @@ public int ConnectionPort public static NatsServer StartJS(ITestOutputHelper outputHelper, TransportType transportType) => Start( outputHelper: outputHelper, - options: new NatsServerOptionsBuilder() + opts: new NatsServerOptsBuilder() .UseTransport(transportType) .UseJetStream() .Build()); @@ -149,9 +149,9 @@ public static NatsServer StartJS(ITestOutputHelper outputHelper, TransportType t public static NatsServer Start(ITestOutputHelper outputHelper) => Start(outputHelper, TransportType.Tcp); public static NatsServer Start(ITestOutputHelper outputHelper, TransportType transportType) => - Start(outputHelper, new NatsServerOptionsBuilder().UseTransport(transportType).Build()); + Start(outputHelper, new NatsServerOptsBuilder().UseTransport(transportType).Build()); - public static NatsServer Start(ITestOutputHelper outputHelper, NatsServerOptions options, NatsOpts? clientOptions = default) + public static NatsServer Start(ITestOutputHelper outputHelper, NatsServerOpts opts, NatsOpts? clientOpts = default) { NatsServer? server = null; NatsConnection? nats = null; @@ -159,8 +159,8 @@ public static NatsServer Start(ITestOutputHelper outputHelper, NatsServerOptions { try { - server = new NatsServer(outputHelper, options); - nats = server.CreateClientConnection(clientOptions ?? NatsOpts.Default, reTryCount: 3); + server = new NatsServer(outputHelper, opts); + nats = server.CreateClientConnection(clientOpts ?? NatsOpts.Default, reTryCount: 3); #pragma warning disable CA2012 return server; } @@ -192,7 +192,7 @@ public async ValueTask DisposeAsync() var processLogs = await _processErr; // wait for process exit, nats output info to stderror if (processLogs.Length != 0) { - _outputHelper.WriteLine("Process Logs of " + Options.ServerPort); + _outputHelper.WriteLine("Process Logs of " + Opts.ServerPort); foreach (var item in processLogs) { _outputHelper.WriteLine(item); @@ -221,21 +221,21 @@ public async ValueTask DisposeAsync() } } - if (Options.ServerDisposeReturnsPorts) + if (Opts.ServerDisposeReturnsPorts) { - Options.Dispose(); + Opts.Dispose(); } } } public (NatsConnection, NatsProxy) CreateProxiedClientConnection(NatsOpts? options = null) { - if (Options.EnableTls) + if (Opts.EnableTls) { throw new Exception("Tapped mode doesn't work wit TLS"); } - var proxy = new NatsProxy(Options.ServerPort, _outputHelper, Options.Trace); + var proxy = new NatsProxy(Opts.ServerPort, _outputHelper, Opts.Trace); var client = new NatsConnection((options ?? NatsOpts.Default) with { @@ -253,7 +253,7 @@ public NatsConnection CreateClientConnection(NatsOpts? options = default, int re { try { - var nats = new NatsConnection(ClientOptions(options ?? NatsOpts.Default)); + var nats = new NatsConnection(ClientOpts(options ?? NatsOpts.Default)); try { @@ -285,10 +285,10 @@ public NatsConnection CreateClientConnection(NatsOpts? options = default, int re public NatsConnectionPool CreatePooledClientConnection(NatsOpts opts) { - return new NatsConnectionPool(4, ClientOptions(opts)); + return new NatsConnectionPool(4, ClientOpts(opts)); } - public NatsOpts ClientOptions(NatsOpts opts) + public NatsOpts ClientOpts(NatsOpts opts) { return opts with { @@ -297,14 +297,14 @@ public NatsOpts ClientOptions(NatsOpts opts) // ConnectTimeout = TimeSpan.FromSeconds(1), // ReconnectWait = TimeSpan.Zero, // ReconnectJitter = TimeSpan.Zero, - TlsOptions = Options.EnableTls - ? TlsOptions.Default with + TlsOpts = Opts.EnableTls + ? NatsTlsOpts.Default with { - CertFile = Options.TlsClientCertFile, - KeyFile = Options.TlsClientKeyFile, - CaFile = Options.TlsCaFile, + CertFile = Opts.TlsClientCertFile, + KeyFile = Opts.TlsClientKeyFile, + CaFile = Opts.TlsCaFile, } - : TlsOptions.Default, + : NatsTlsOpts.Default, Url = ClientUrl, }; } @@ -331,19 +331,19 @@ public class NatsCluster : IAsyncDisposable { public NatsCluster(ITestOutputHelper outputHelper, TransportType transportType) { - var opts1 = new NatsServerOptions + var opts1 = new NatsServerOpts { TransportType = transportType, EnableWebSocket = transportType == TransportType.WebSocket, EnableClustering = true, }; - var opts2 = new NatsServerOptions + var opts2 = new NatsServerOpts { TransportType = transportType, EnableWebSocket = transportType == TransportType.WebSocket, EnableClustering = true, }; - var opts3 = new NatsServerOptions + var opts3 = new NatsServerOpts { TransportType = transportType, EnableWebSocket = transportType == TransportType.WebSocket, diff --git a/tests/NATS.Client.TestUtilities/NatsServerOptions.cs b/tests/NATS.Client.TestUtilities/NatsServerOpts.cs similarity index 92% rename from tests/NATS.Client.TestUtilities/NatsServerOptions.cs rename to tests/NATS.Client.TestUtilities/NatsServerOpts.cs index 32a6d094e..7d16e1b72 100644 --- a/tests/NATS.Client.TestUtilities/NatsServerOptions.cs +++ b/tests/NATS.Client.TestUtilities/NatsServerOpts.cs @@ -11,7 +11,7 @@ public enum TransportType WebSocket, } -public sealed class NatsServerOptionsBuilder +public sealed class NatsServerOptsBuilder { private readonly List _extraConfigs = new(); private bool _enableWebSocket; @@ -23,9 +23,9 @@ public sealed class NatsServerOptionsBuilder private TransportType? _transportType; private bool _trace; - public NatsServerOptions Build() + public NatsServerOpts Build() { - return new NatsServerOptions + return new NatsServerOpts { EnableWebSocket = _enableWebSocket, EnableTls = _enableTls, @@ -39,13 +39,13 @@ public NatsServerOptions Build() }; } - public NatsServerOptionsBuilder Trace() + public NatsServerOptsBuilder Trace() { _trace = true; return this; } - public NatsServerOptionsBuilder UseTransport(TransportType transportType) + public NatsServerOptsBuilder UseTransport(TransportType transportType) { _transportType = transportType; @@ -64,20 +64,20 @@ public NatsServerOptionsBuilder UseTransport(TransportType transportType) return this; } - public NatsServerOptionsBuilder UseJetStream() + public NatsServerOptsBuilder UseJetStream() { _enableJetStream = true; return this; } - public NatsServerOptionsBuilder AddServerConfig(string config) + public NatsServerOptsBuilder AddServerConfig(string config) { _extraConfigs.Add(File.ReadAllText(config)); return this; } } -public sealed class NatsServerOptions : IDisposable +public sealed class NatsServerOpts : IDisposable { private static readonly Lazy> PortFactory = new(() => { @@ -101,7 +101,7 @@ public sealed class NatsServerOptions : IDisposable private int _disposed; private string _routes = string.Empty; - public NatsServerOptions() + public NatsServerOpts() { _lazyServerPort = new Lazy(LeasePort); _lazyClusteringPort = new Lazy(() => EnableClustering ? LeasePort() : null); @@ -203,7 +203,7 @@ public string ConfigFileContents } } - public void SetRoutes(IEnumerable options) + public void SetRoutes(IEnumerable options) { _routes = string.Join(",", options.Select(o => $"nats://localhost:{o.ClusteringPort}")); }