diff --git a/README.md b/README.md index 67676ce4b..11d814f4f 100755 --- a/README.md +++ b/README.md @@ -490,7 +490,7 @@ opts.AsyncErrorEventHandler += (sender, args) => opts.ServerDiscoveredEventHandler += (sender, args) => { Console.WriteLine("A new server has joined the cluster:"); - Console.WriteLine(" " + String.Join(", ", args.Conn.DiscoveredServers)); + Console.WriteLine(" " + string.Join(", ", args.Conn.DiscoveredServers)); }; opts.ClosedEventHandler += (sender, args) => diff --git a/src/Benchmarks/JsMulti/JsMultiTool.cs b/src/Benchmarks/JsMulti/JsMultiTool.cs index b27f41a6b..8c95b533a 100644 --- a/src/Benchmarks/JsMulti/JsMultiTool.cs +++ b/src/Benchmarks/JsMulti/JsMultiTool.cs @@ -31,7 +31,7 @@ public static void Main(string[] args) Run(new Context(args), false, true); } - public static IList Run(String[] args) { + public static IList Run(string[] args) { return Run(new Context(args), false, true); } @@ -382,11 +382,11 @@ private static void _ack(Stats stats, Msg m) { stats.Stop(); } - private static void Report(string label, int total, String message) { + private static void Report(string label, int total, string message) { Log(label, message + " " + Stats.Format(total)); } - private static int ReportMaybe(string label, Context ctx, int total, int unReported, String message) { + private static int ReportMaybe(string label, Context ctx, int total, int unReported, string message) { if (unReported >= ctx.ReportFrequency) { Report(label, total, message); return 0; // there are 0 unreported now diff --git a/src/Benchmarks/JsMulti/Settings/Arguments.cs b/src/Benchmarks/JsMulti/Settings/Arguments.cs index fdad60225..3a32b4e04 100644 --- a/src/Benchmarks/JsMulti/Settings/Arguments.cs +++ b/src/Benchmarks/JsMulti/Settings/Arguments.cs @@ -25,24 +25,24 @@ public class Arguments public const string Individual = "individual"; public const string Shared = "shared"; - private IList args = new List(); + private IList args = new List(); public static Arguments Instance() { return new Arguments(); } - public static Arguments Instance(String subject) { return Instance().Subject(subject); } - public static Arguments PubSync(String subject) { return Instance().Action(JsmAction.PubSync).Subject(subject); } - public static Arguments PubAsync(String subject) { return Instance().Action(JsmAction.PubAsync).Subject(subject); } - public static Arguments PubCore(String subject) { return Instance().Action(JsmAction.PubCore).Subject(subject); } - public static Arguments SubPush(String subject) { return Instance().Action(JsmAction.SubPush).Subject(subject); } - public static Arguments SubQueue(String subject) { return Instance().Action(JsmAction.SubQueue).Subject(subject); } - public static Arguments SubPull(String subject) { return Instance().Action(JsmAction.SubPull).Subject(subject); } - public static Arguments SubPullQueue(String subject) { return Instance().Action(JsmAction.SubPullQueue).Subject(subject); } - - private Arguments Add(String option) { + public static Arguments Instance(string subject) { return Instance().Subject(subject); } + public static Arguments PubSync(string subject) { return Instance().Action(JsmAction.PubSync).Subject(subject); } + public static Arguments PubAsync(string subject) { return Instance().Action(JsmAction.PubAsync).Subject(subject); } + public static Arguments PubCore(string subject) { return Instance().Action(JsmAction.PubCore).Subject(subject); } + public static Arguments SubPush(string subject) { return Instance().Action(JsmAction.SubPush).Subject(subject); } + public static Arguments SubQueue(string subject) { return Instance().Action(JsmAction.SubQueue).Subject(subject); } + public static Arguments SubPull(string subject) { return Instance().Action(JsmAction.SubPull).Subject(subject); } + public static Arguments SubPullQueue(string subject) { return Instance().Action(JsmAction.SubPullQueue).Subject(subject); } + + private Arguments Add(string option) { args.Add("-" + option); return this; } - private Arguments Add(String option, Object value) { + private Arguments Add(string option, Object value) { args.Add("-" + option); args.Add(value.ToString()); return this; @@ -52,7 +52,7 @@ public Arguments Action(JsmAction action) { return Add("a", action); } - public Arguments Server(String server) { + public Arguments Server(string server) { return Add("s", server); } @@ -65,7 +65,7 @@ public Arguments LatencyFlag(bool lf) { } // todo - // public ArgumentBuilder OptionsFactory(String optionsFactoryClassName) { + // public ArgumentBuilder OptionsFactory(string optionsFactoryClassName) { // return Add("of", optionsFactoryClassName); // } @@ -93,7 +93,7 @@ public Arguments Replicas(int replicas) { return Add("c", replicas); } - public Arguments Subject(String subject) { + public Arguments Subject(string subject) { if (subject == null) { return this; } @@ -162,7 +162,7 @@ public string[] ToArray() } public void PrintCommandLine(TextWriter ps) { - foreach (String a in args) { + foreach (string a in args) { ps.Write(a + " "); } ps.WriteLine(""); diff --git a/src/NATS.Client/Connection.cs b/src/NATS.Client/Connection.cs index 165f7a58d..001b54cae 100644 --- a/src/NATS.Client/Connection.cs +++ b/src/NATS.Client/Connection.cs @@ -1031,7 +1031,7 @@ public IPAddress ClientIP clientIp = info.ClientIp; } - return !String.IsNullOrEmpty(clientIp) ? IPAddress.Parse(clientIp) : null; + return !string.IsNullOrEmpty(clientIp) ? IPAddress.Parse(clientIp) : null; } } diff --git a/src/NATS.Client/IConnection.cs b/src/NATS.Client/IConnection.cs index b82ed9291..85c451a28 100644 --- a/src/NATS.Client/IConnection.cs +++ b/src/NATS.Client/IConnection.cs @@ -1108,7 +1108,6 @@ public interface IConnection : IDisposable /// /// Get a consumer context for a specific named stream and specific named consumer. /// Verifies that the stream and consumer exist. - /// EXPERIMENTAL API SUBJECT TO CHANGE /// /// the name of the stream /// the name of the consumer @@ -1118,7 +1117,6 @@ public interface IConnection : IDisposable /// /// Get a consumer context for a specific named stream and specific named consumer. /// Verifies that the stream and consumer exist. - /// EXPERIMENTAL API SUBJECT TO CHANGE /// /// the name of the stream /// the name of the consumer diff --git a/src/NATS.Client/Internals/JsonUtils.cs b/src/NATS.Client/Internals/JsonUtils.cs index eff9534a2..8a43a7d4d 100644 --- a/src/NATS.Client/Internals/JsonUtils.cs +++ b/src/NATS.Client/Internals/JsonUtils.cs @@ -97,14 +97,14 @@ public static List OptionalStringList(JSONNode node, string field) } [Obsolete("Method name replaced with proper spelling, 'StringStringDictionary'")] - public static Dictionary StringStringDictionay(JSONNode node, string field) + public static IDictionary StringStringDictionay(JSONNode node, string field) { return StringStringDictionary(node, field, false); } - public static Dictionary StringStringDictionary(JSONNode node, string field, bool nullIfEmpty = false) + public static IDictionary StringStringDictionary(JSONNode node, string field, bool nullIfEmpty = false) { - Dictionary temp = new Dictionary(); + IDictionary temp = new Dictionary(); JSONNode meta = node[field]; foreach (string key in meta.Keys) { @@ -244,7 +244,7 @@ public static void AddField(JSONObject o, string field, JSONNode value) } } - public static void AddField(JSONObject o, String fname, Dictionary dictionary) { + public static void AddField(JSONObject o, string fname, IDictionary dictionary) { if (dictionary != null && dictionary.Count > 0) { JSONObject d = new JSONObject(); foreach (string key in dictionary.Keys) diff --git a/src/NATS.Client/Internals/JwtUtils.cs b/src/NATS.Client/Internals/JwtUtils.cs index 3b8169cc1..0969623cc 100644 --- a/src/NATS.Client/Internals/JwtUtils.cs +++ b/src/NATS.Client/Internals/JwtUtils.cs @@ -36,8 +36,8 @@ public static class JwtUtils ///
         /// NKey userKey = NKey.createUser(new SecureRandom());
         /// NKey signingKey = loadFromSecretStore();
-        /// String jwt = IssueUserJWT(signingKey, accountId, userKey.EncodedPublicKey);
-        /// String.format(JwtUtils.NatsUserJwtFormat, jwt, userKey.EncodedSeed);
+        /// string jwt = IssueUserJWT(signingKey, accountId, userKey.EncodedPublicKey);
+        /// string.format(JwtUtils.NatsUserJwtFormat, jwt, userKey.EncodedSeed);
         /// 
/// public static readonly string NatsUserJwtFormat = @@ -112,7 +112,7 @@ public static string IssueUserJWT(NkeyPair signingKey, string accountId, string /// optional list of tags to be included in the JWT. /// the current epoch seconds. /// a JWT - public static string IssueUserJWT(NkeyPair signingKey, string accountId, string publicUserKey, string name, Duration expiration, String[] tags, long issuedAt) + public static string IssueUserJWT(NkeyPair signingKey, string accountId, string publicUserKey, string name, Duration expiration, string[] tags, long issuedAt) { return IssueUserJWT(signingKey, publicUserKey, name, expiration, issuedAt, null, new UserClaim(accountId, tags)); } @@ -129,7 +129,7 @@ public static string IssueUserJWT(NkeyPair signingKey, string accountId, string /// the current epoch seconds. /// optional audience /// a JWT - public static string IssueUserJWT(NkeyPair signingKey, string accountId, string publicUserKey, string name, Duration expiration, String[] tags, long issuedAt, string audience) + public static string IssueUserJWT(NkeyPair signingKey, string accountId, string publicUserKey, string name, Duration expiration, string[] tags, long issuedAt, string audience) { return IssueUserJWT(signingKey, publicUserKey, name, expiration, issuedAt, audience, new UserClaim(accountId, tags)); } @@ -145,7 +145,7 @@ public static string IssueUserJWT(NkeyPair signingKey, string accountId, string /// optional audience /// the user claim /// a JWT - public static string IssueUserJWT(NkeyPair signingKey, string publicUserKey, string name, Duration expiration, long issuedAt, String audience, UserClaim nats) + public static string IssueUserJWT(NkeyPair signingKey, string publicUserKey, string name, Duration expiration, long issuedAt, string audience, UserClaim nats) { // Validate the signingKey: if (signingKey.Type != Nkeys.PrefixType.Account) @@ -226,7 +226,7 @@ public static string issueJWT(NkeyPair signingKey, string publicUserKey, string /// /// the encoded jwt /// the claim body json - public static string GetClaimBody(String jwt) + public static string GetClaimBody(string jwt) { return FromBase64UrlEncoded(jwt.Split('.')[1]); } @@ -234,26 +234,26 @@ public static string GetClaimBody(String jwt) public class UserClaim : JsonSerializable { public string IssuerAccount; // User - public String[] Tags; // User/GenericFields + public string[] Tags; // User/GenericFields public string Type = "user"; // User/GenericFields public int Version = 2; // User/GenericFields public Permission Pub; // User/UserPermissionLimits/Permissions public Permission Sub; // User/UserPermissionLimits/Permissions public ResponsePermission Resp; // User/UserPermissionLimits/Permissions - public String[] Src; // User/UserPermissionLimits/Limits/UserLimits + public string[] Src; // User/UserPermissionLimits/Limits/UserLimits public IList Times; // User/UserPermissionLimits/Limits/UserLimits public string Locale; // User/UserPermissionLimits/Limits/UserLimits public long Subs = JwtUtils.NoLimit; // User/UserPermissionLimits/Limits/NatsLimits public long Data = JwtUtils.NoLimit; // User/UserPermissionLimits/Limits/NatsLimits public long Payload = JwtUtils.NoLimit; // User/UserPermissionLimits/Limits/NatsLimits public bool BearerToken; // User/UserPermissionLimits - public String[] AllowedConnectionTypes; // User/UserPermissionLimits + public string[] AllowedConnectionTypes; // User/UserPermissionLimits public UserClaim(string issuerAccount) { this.IssuerAccount = issuerAccount; } - public UserClaim(string issuerAccount, String[] tags) { + public UserClaim(string issuerAccount, string[] tags) { IssuerAccount = issuerAccount; Tags = tags; } diff --git a/src/NATS.Client/Internals/ServerVersion.cs b/src/NATS.Client/Internals/ServerVersion.cs index 2476289ff..b850e7e16 100644 --- a/src/NATS.Client/Internals/ServerVersion.cs +++ b/src/NATS.Client/Internals/ServerVersion.cs @@ -23,7 +23,7 @@ internal class ServerVersion : IComparable { readonly int patch; readonly string extra; - internal ServerVersion(String v) { + internal ServerVersion(string v) { string[] split = v.Replace("v", "").Replace("-", ".").Split('.'); if (v.StartsWith("v")) { split = v.Substring(1).Replace("-", ".").Split('.'); @@ -93,23 +93,23 @@ public int CompareTo(ServerVersion o) return c; } - public static bool IsNewer(String v, String than) { + public static bool IsNewer(string v, string than) { return new ServerVersion(v).CompareTo(new ServerVersion(than)) > 0; } - public static bool IsSame(String v, String than) { + public static bool IsSame(string v, string than) { return new ServerVersion(v).CompareTo(new ServerVersion(than)) == 0; } - public static bool IsOlder(String v, String than) { + public static bool IsOlder(string v, string than) { return new ServerVersion(v).CompareTo(new ServerVersion(than)) < 0; } - public static bool IsSameOrOlder(String v, String than) { + public static bool IsSameOrOlder(string v, string than) { return new ServerVersion(v).CompareTo(new ServerVersion(than)) <= 0; } - public static bool IsSameOrNewer(String v, String than) { + public static bool IsSameOrNewer(string v, string than) { return new ServerVersion(v).CompareTo(new ServerVersion(than)) >= 0; } } diff --git a/src/NATS.Client/Internals/Validator.cs b/src/NATS.Client/Internals/Validator.cs index 1e44bf62c..4acee35f1 100644 --- a/src/NATS.Client/Internals/Validator.cs +++ b/src/NATS.Client/Internals/Validator.cs @@ -39,7 +39,7 @@ internal static void Required(object o, string label) { } } - internal static void Required(Dictionary d, string label) { + internal static void Required(IDictionary d, string label) { if (d == null || d.Count == 0) { throw new ArgumentException($"{label} cannot be null or empty."); } @@ -50,16 +50,16 @@ internal static string ValidateSubject(string s, bool required) return ValidateSubject(s, "Subject", required, false); } - public static String ValidateSubject(String subject, String label, bool required, bool cantEndWithGt) { + public static string ValidateSubject(string subject, string label, bool required, bool cantEndWithGt) { if (EmptyAsNull(subject) == null) { if (required) { throw new ArgumentException($"{label} cannot be null or empty."); } return null; } - String[] segments = subject.Split('.'); + string[] segments = subject.Split('.'); for (int x = 0; x < segments.Length; x++) { - String segment = segments[x]; + string segment = segments[x]; if (segment.Equals(">")) { if (cantEndWithGt || x != segments.Length - 1) { // if it can end with gt, gt must be last segment throw new ArgumentException(label + " cannot contain '>'"); @@ -445,7 +445,7 @@ internal static long ValidateNotNegative(long l, string label) { // Helpers // ---------------------------------------------------------------------------------------------------- - public static bool NullOrEmpty(String s) + public static bool NullOrEmpty(string s) { return string.IsNullOrWhiteSpace(s); } @@ -607,7 +607,7 @@ public static string EmptyAsNull(string s) return NullOrEmpty(s) ? null : s; } - public static String EmptyOrNullAs(String s, String ifEmpty) { + public static string EmptyOrNullAs(string s, string ifEmpty) { return NullOrEmpty(s) ? ifEmpty : s; } @@ -658,7 +658,7 @@ public static string ValidateSemVer(string s, string label, bool required) }); } - public static bool IsSemVer(String s) + public static bool IsSemVer(string s) { return Regex.IsMatch(s, SemVerPattern); } diff --git a/src/NATS.Client/JetStream/ApiConstants.cs b/src/NATS.Client/JetStream/ApiConstants.cs index 32abe8626..4a58fe3f2 100644 --- a/src/NATS.Client/JetStream/ApiConstants.cs +++ b/src/NATS.Client/JetStream/ApiConstants.cs @@ -22,7 +22,6 @@ internal static class ApiConstants internal const string AllowRollupHdrs = "allow_rollup_hdrs"; internal const string AllowDirect = "allow_direct"; internal const string Api = "api"; - internal const string ApiUrl = "api_url"; internal const string AuthRequired = "auth_required"; internal const string AverageProcessingTime = "average_processing_time"; internal const string Backoff = "backoff"; diff --git a/src/NATS.Client/JetStream/BaseConsumeOptions.cs b/src/NATS.Client/JetStream/BaseConsumeOptions.cs index b52220623..a9d1b002d 100644 --- a/src/NATS.Client/JetStream/BaseConsumeOptions.cs +++ b/src/NATS.Client/JetStream/BaseConsumeOptions.cs @@ -18,7 +18,6 @@ namespace NATS.Client.JetStream /// /// Base Consume Options are provided to customize the way the consume and /// fetch operate. It is the base class for ConsumeOptions and FetchConsumeOptions. - /// SIMPLIFICATION IS EXPERIMENTAL AND SUBJECT TO CHANGE /// public class BaseConsumeOptions { diff --git a/src/NATS.Client/JetStream/ConsumeOptions.cs b/src/NATS.Client/JetStream/ConsumeOptions.cs index 733d9a6c0..45908ffdf 100644 --- a/src/NATS.Client/JetStream/ConsumeOptions.cs +++ b/src/NATS.Client/JetStream/ConsumeOptions.cs @@ -15,7 +15,6 @@ namespace NATS.Client.JetStream { /// /// Consume Options are provided to customize the consume operation. - /// SIMPLIFICATION IS EXPERIMENTAL AND SUBJECT TO CHANGE /// public class ConsumeOptions : BaseConsumeOptions { diff --git a/src/NATS.Client/JetStream/ConsumerConfiguration.cs b/src/NATS.Client/JetStream/ConsumerConfiguration.cs index 4dfc3c72f..1ea136a87 100644 --- a/src/NATS.Client/JetStream/ConsumerConfiguration.cs +++ b/src/NATS.Client/JetStream/ConsumerConfiguration.cs @@ -55,7 +55,7 @@ public sealed class ConsumerConfiguration : JsonSerializable internal bool? _headersOnly; internal bool? _memStorage; internal IList _backoff; - internal Dictionary _metadata; + internal IDictionary _metadata; public DeliverPolicy DeliverPolicy => _deliverPolicy ?? DeliverPolicy.All; public AckPolicy AckPolicy => _ackPolicy ?? AckPolicy.Explicit; @@ -87,7 +87,7 @@ public sealed class ConsumerConfiguration : JsonSerializable public bool HeadersOnly => _headersOnly ?? false; public bool MemStorage => _memStorage ?? false; public IList Backoff => _backoff ?? new List(); - public Dictionary Metadata => _metadata ?? new Dictionary(); + public IDictionary Metadata => _metadata ?? new Dictionary(); internal ConsumerConfiguration(string json) : this(JSON.Parse(json)) {} diff --git a/src/NATS.Client/JetStream/ConsumerContext.cs b/src/NATS.Client/JetStream/ConsumerContext.cs index 25d4f5800..6dd6f0fb6 100644 --- a/src/NATS.Client/JetStream/ConsumerContext.cs +++ b/src/NATS.Client/JetStream/ConsumerContext.cs @@ -33,7 +33,7 @@ internal OrderedPullSubscribeOptionsBuilder(string streamName, ConsumerConfigura } /// - /// SIMPLIFICATION IS EXPERIMENTAL AND SUBJECT TO CHANGE + /// Implementation of IConsumerContext /// internal class ConsumerContext : IConsumerContext, SimplifiedSubscriptionMaker { diff --git a/src/NATS.Client/JetStream/FetchConsumeOptions.cs b/src/NATS.Client/JetStream/FetchConsumeOptions.cs index 4bc3d7263..d43718a7a 100644 --- a/src/NATS.Client/JetStream/FetchConsumeOptions.cs +++ b/src/NATS.Client/JetStream/FetchConsumeOptions.cs @@ -15,7 +15,6 @@ namespace NATS.Client.JetStream { /// /// Consume Options are provided to customize the consume operation. - /// SIMPLIFICATION IS EXPERIMENTAL AND SUBJECT TO CHANGE /// public class FetchConsumeOptions : BaseConsumeOptions { diff --git a/src/NATS.Client/JetStream/FetchConsumer.cs b/src/NATS.Client/JetStream/FetchConsumer.cs index dbf1957f3..e0c97a9d9 100644 --- a/src/NATS.Client/JetStream/FetchConsumer.cs +++ b/src/NATS.Client/JetStream/FetchConsumer.cs @@ -16,7 +16,7 @@ namespace NATS.Client.JetStream { /// - /// SIMPLIFICATION IS EXPERIMENTAL AND SUBJECT TO CHANGE + /// Implementation of IFetchConsumer /// internal class FetchConsumer : MessageConsumerBase, IFetchConsumer { diff --git a/src/NATS.Client/JetStream/IBaseConsumerContext.cs b/src/NATS.Client/JetStream/IBaseConsumerContext.cs index 71b9226ab..b33bca6b0 100644 --- a/src/NATS.Client/JetStream/IBaseConsumerContext.cs +++ b/src/NATS.Client/JetStream/IBaseConsumerContext.cs @@ -3,8 +3,7 @@ namespace NATS.Client.JetStream { /// - /// The Consumer Context provides a convenient interface around a defined JetStream Consumer - /// SIMPLIFICATION IS EXPERIMENTAL AND SUBJECT TO CHANGE + /// Base class for IConsumerContext implementations /// public interface IBaseConsumerContext { diff --git a/src/NATS.Client/JetStream/IConsumerContext.cs b/src/NATS.Client/JetStream/IConsumerContext.cs index 7581bf55e..7516b5f10 100644 --- a/src/NATS.Client/JetStream/IConsumerContext.cs +++ b/src/NATS.Client/JetStream/IConsumerContext.cs @@ -15,7 +15,6 @@ namespace NATS.Client.JetStream { /// /// The Consumer Context provides a convenient interface around a defined JetStream Consumer - /// SIMPLIFICATION IS EXPERIMENTAL AND SUBJECT TO CHANGE /// public interface IConsumerContext : IBaseConsumerContext { diff --git a/src/NATS.Client/JetStream/IFetchConsumer.cs b/src/NATS.Client/JetStream/IFetchConsumer.cs index 622a103d7..2ace0ae22 100644 --- a/src/NATS.Client/JetStream/IFetchConsumer.cs +++ b/src/NATS.Client/JetStream/IFetchConsumer.cs @@ -14,7 +14,7 @@ namespace NATS.Client.JetStream { /// - /// SIMPLIFICATION IS EXPERIMENTAL AND SUBJECT TO CHANGE + /// Interface definition for a Fetch Consumer /// public interface IFetchConsumer : IMessageConsumer { diff --git a/src/NATS.Client/JetStream/IIterableConsumer.cs b/src/NATS.Client/JetStream/IIterableConsumer.cs index 4163b89c4..2d79c322e 100644 --- a/src/NATS.Client/JetStream/IIterableConsumer.cs +++ b/src/NATS.Client/JetStream/IIterableConsumer.cs @@ -14,7 +14,7 @@ namespace NATS.Client.JetStream { /// - /// SIMPLIFICATION IS EXPERIMENTAL AND SUBJECT TO CHANGE + /// Interface definition for a Iterable Consumer /// public interface IIterableConsumer : IMessageConsumer { diff --git a/src/NATS.Client/JetStream/IJetStream.cs b/src/NATS.Client/JetStream/IJetStream.cs index b92506361..db587d495 100644 --- a/src/NATS.Client/JetStream/IJetStream.cs +++ b/src/NATS.Client/JetStream/IJetStream.cs @@ -398,7 +398,6 @@ public interface IJetStream /// /// Create a stream context for a specific named stream. Verifies that the stream exists. - /// EXPERIMENTAL API SUBJECT TO CHANGE /// /// the name of the stream /// an IStreamContext instance @@ -407,7 +406,6 @@ public interface IJetStream /// /// Create a consumer context for a specific named stream and specific named consumer. /// Verifies that the stream and consumer exist. - /// EXPERIMENTAL API SUBJECT TO CHANGE /// /// the name of the stream /// the name of the consumer diff --git a/src/NATS.Client/JetStream/IMessageConsumer.cs b/src/NATS.Client/JetStream/IMessageConsumer.cs index d7c13f2fe..626d0ae30 100644 --- a/src/NATS.Client/JetStream/IMessageConsumer.cs +++ b/src/NATS.Client/JetStream/IMessageConsumer.cs @@ -16,7 +16,7 @@ namespace NATS.Client.JetStream { /// - /// SIMPLIFICATION IS EXPERIMENTAL AND SUBJECT TO CHANGE + /// Interface definition for a Message Consumer /// public interface IMessageConsumer : IDisposable { diff --git a/src/NATS.Client/JetStream/IOrderedConsumerContext.cs b/src/NATS.Client/JetStream/IOrderedConsumerContext.cs index f29dea6ed..b48134af7 100644 --- a/src/NATS.Client/JetStream/IOrderedConsumerContext.cs +++ b/src/NATS.Client/JetStream/IOrderedConsumerContext.cs @@ -14,8 +14,7 @@ namespace NATS.Client.JetStream { /// - /// The Consumer Context provides a convenient interface around a defined JetStream Consumer - /// SIMPLIFICATION IS EXPERIMENTAL AND SUBJECT TO CHANGE + /// The Ordered Consumer and it's context provide a simplification interface to the ordered consumer behavior. /// public interface IOrderedConsumerContext : IBaseConsumerContext { diff --git a/src/NATS.Client/JetStream/IStreamContext.cs b/src/NATS.Client/JetStream/IStreamContext.cs index 9232479f4..94b132343 100644 --- a/src/NATS.Client/JetStream/IStreamContext.cs +++ b/src/NATS.Client/JetStream/IStreamContext.cs @@ -18,7 +18,6 @@ namespace NATS.Client.JetStream /// /// The Stream Context provide a set of operations for managing the stream /// and its contents and for managing consumers. - /// SIMPLIFICATION IS EXPERIMENTAL AND SUBJECT TO CHANGE /// public interface IStreamContext { diff --git a/src/NATS.Client/JetStream/IterableConsumer.cs b/src/NATS.Client/JetStream/IterableConsumer.cs index e02edf5bf..e0b628d40 100644 --- a/src/NATS.Client/JetStream/IterableConsumer.cs +++ b/src/NATS.Client/JetStream/IterableConsumer.cs @@ -14,7 +14,7 @@ namespace NATS.Client.JetStream { /// - /// SIMPLIFICATION IS EXPERIMENTAL AND SUBJECT TO CHANGE + /// Implementation for IIterableConsumer /// internal class IterableConsumer : MessageConsumer, IIterableConsumer { diff --git a/src/NATS.Client/JetStream/JetStreamAbstractSyncSubscription.cs b/src/NATS.Client/JetStream/JetStreamAbstractSyncSubscription.cs index 1b0532957..5175ff773 100644 --- a/src/NATS.Client/JetStream/JetStreamAbstractSyncSubscription.cs +++ b/src/NATS.Client/JetStream/JetStreamAbstractSyncSubscription.cs @@ -11,7 +11,6 @@ // See the License for the specific language governing permissions and // limitations under the License. -using System; using System.Diagnostics; namespace NATS.Client.JetStream @@ -88,7 +87,7 @@ public override Msg NextMessage(int timeout) return _nextUnmanaged(timeout, null); } - internal Msg _nextUnmanagedWaitForever(String expectedPullSubject) + internal Msg _nextUnmanagedWaitForever(string expectedPullSubject) { // this calls is intended to block indefinitely so if there is a managed // message it's like not getting a message at all and we keep waiting diff --git a/src/NATS.Client/JetStream/MessageConsumer.cs b/src/NATS.Client/JetStream/MessageConsumer.cs index 9e7059987..46ba72e47 100644 --- a/src/NATS.Client/JetStream/MessageConsumer.cs +++ b/src/NATS.Client/JetStream/MessageConsumer.cs @@ -17,7 +17,7 @@ namespace NATS.Client.JetStream { /// - /// SIMPLIFICATION IS EXPERIMENTAL AND SUBJECT TO CHANGE + /// Interface definition for a Message Consumer /// internal class MessageConsumer : MessageConsumerBase, IPullManagerObserver { diff --git a/src/NATS.Client/JetStream/MessageConsumerBase.cs b/src/NATS.Client/JetStream/MessageConsumerBase.cs index e9879318a..5e9be628b 100644 --- a/src/NATS.Client/JetStream/MessageConsumerBase.cs +++ b/src/NATS.Client/JetStream/MessageConsumerBase.cs @@ -17,7 +17,7 @@ namespace NATS.Client.JetStream { /// - /// SIMPLIFICATION IS EXPERIMENTAL AND SUBJECT TO CHANGE + /// Base class for Message Consumer implementations /// internal class MessageConsumerBase : IMessageConsumer { diff --git a/src/NATS.Client/JetStream/MessageInfo.cs b/src/NATS.Client/JetStream/MessageInfo.cs index f25dd5c31..d32f712f7 100644 --- a/src/NATS.Client/JetStream/MessageInfo.cs +++ b/src/NATS.Client/JetStream/MessageInfo.cs @@ -30,7 +30,7 @@ public sealed class MessageInfo : ApiResponse [Obsolete("This property is obsolete. Use Sequence instead.", false)] public long Seq => Convert.ToInt64(Sequence); - internal MessageInfo(Msg msg, String streamName, bool fromDirect, bool throwOnError) : base(msg, throwOnError, fromDirect) + internal MessageInfo(Msg msg, string streamName, bool fromDirect, bool throwOnError) : base(msg, throwOnError, fromDirect) { Init(msg, fromDirect, streamName); } @@ -40,7 +40,7 @@ public MessageInfo(string json) : base(json) Init(null, false, null); } - private void Init(Msg msg, bool fromDirect, String streamName) + private void Init(Msg msg, bool fromDirect, string streamName) { if (fromDirect) { @@ -50,7 +50,7 @@ private void Init(Msg msg, bool fromDirect, String streamName) Sequence = ulong.Parse(msg.Header[JetStreamConstants.NatsSequence]); Time = JsonUtils.AsDate(msg.Header[JetStreamConstants.NatsTimestamp]); Stream = msg.Header[JetStreamConstants.NatsStream]; - String temp = msg.Header[JetStreamConstants.NatsLastSequence]; + string temp = msg.Header[JetStreamConstants.NatsLastSequence]; if (temp != null) { LastSequence = ulong.Parse(temp); diff --git a/src/NATS.Client/JetStream/OrderedConsumerContext.cs b/src/NATS.Client/JetStream/OrderedConsumerContext.cs index 032cd15fc..162f6cf75 100644 --- a/src/NATS.Client/JetStream/OrderedConsumerContext.cs +++ b/src/NATS.Client/JetStream/OrderedConsumerContext.cs @@ -3,7 +3,7 @@ namespace NATS.Client.JetStream { /// - /// SIMPLIFICATION IS EXPERIMENTAL AND SUBJECT TO CHANGE + /// Implementation for the IOrderedConsumerContext /// internal class OrderedConsumerContext : IOrderedConsumerContext { diff --git a/src/NATS.Client/JetStream/PushMessageManager.cs b/src/NATS.Client/JetStream/PushMessageManager.cs index f319356b8..3eda3f7ac 100644 --- a/src/NATS.Client/JetStream/PushMessageManager.cs +++ b/src/NATS.Client/JetStream/PushMessageManager.cs @@ -11,7 +11,6 @@ // See the License for the specific language governing permissions and // limitations under the License. -using System; using NATS.Client.Internals; namespace NATS.Client.JetStream @@ -19,7 +18,7 @@ namespace NATS.Client.JetStream public class PushMessageManager : MessageManager { protected readonly JetStream Js; - protected readonly String Stream; + protected readonly string Stream; protected readonly ConsumerConfiguration OriginalCc; protected readonly bool QueueMode; @@ -79,7 +78,7 @@ protected bool hasFcSubject(Msg msg) { return msg.Header != null && msg.Header[JetStreamConstants.ConsumerStalledHeader] != null; } - protected String extractFcSubject(Msg msg) { + protected string extractFcSubject(Msg msg) { return msg.Header == null ? null : msg.Header[JetStreamConstants.ConsumerStalledHeader]; } @@ -98,7 +97,7 @@ protected ManageResult ManageStatus(Msg msg) { // otherwise they are simply known statuses if (Fc) { bool isFlowControl = msg.Status.IsFlowControl(); - String fcSubject = isFlowControl ? msg.Reply : extractFcSubject(msg); + string fcSubject = isFlowControl ? msg.Reply : extractFcSubject(msg); if (fcSubject != null) { _processFlowControl(fcSubject, isFlowControl ? FlowControlSource.FlowControl : FlowControlSource.Heartbeat); return ManageResult.StatusHandled; diff --git a/src/NATS.Client/JetStream/StreamConfiguration.cs b/src/NATS.Client/JetStream/StreamConfiguration.cs index f90667390..b6792a544 100644 --- a/src/NATS.Client/JetStream/StreamConfiguration.cs +++ b/src/NATS.Client/JetStream/StreamConfiguration.cs @@ -48,7 +48,7 @@ public sealed class StreamConfiguration : JsonSerializable public bool DenyDelete { get; } public bool DenyPurge { get; } public bool DiscardNewPerSubject { get; } - public Dictionary Metadata { get; } + public IDictionary Metadata { get; } [Obsolete("MaxMsgSize was mistakenly renamed in a previous change.", false)] public long MaxValueSize => MaxMsgSize; diff --git a/src/NATS.Client/JetStream/StreamContext.cs b/src/NATS.Client/JetStream/StreamContext.cs index 283128be9..8ff84cd17 100644 --- a/src/NATS.Client/JetStream/StreamContext.cs +++ b/src/NATS.Client/JetStream/StreamContext.cs @@ -16,7 +16,7 @@ namespace NATS.Client.JetStream { /// - /// SIMPLIFICATION IS EXPERIMENTAL AND SUBJECT TO CHANGE + /// Implementation for IStreamContext /// internal class StreamContext : IStreamContext { diff --git a/src/NATS.Client/JetStream/Subject.cs b/src/NATS.Client/JetStream/Subject.cs index 83bb9f9d2..73359d30a 100644 --- a/src/NATS.Client/JetStream/Subject.cs +++ b/src/NATS.Client/JetStream/Subject.cs @@ -11,7 +11,6 @@ // See the License for the specific language governing permissions and // limitations under the License. -using System; using System.Collections.Generic; using NATS.Client.Internals.SimpleJSON; @@ -30,7 +29,7 @@ internal static IList GetList(JSONNode subjectsNode) JSONNode.Enumerator e = subjectsNode.GetEnumerator(); while (e.MoveNext()) { - KeyValuePair pair = e.Current; + KeyValuePair pair = e.Current; list.Add(new Subject(pair.Key, pair.Value.AsLong)); } } diff --git a/src/NATS.Client/Msg.cs b/src/NATS.Client/Msg.cs index 7e6360a03..3a2575d50 100644 --- a/src/NATS.Client/Msg.cs +++ b/src/NATS.Client/Msg.cs @@ -246,7 +246,7 @@ public ISubscription ArrivalSubscription /// public void Respond(byte[] data) { - if (String.IsNullOrEmpty(Reply)) + if (string.IsNullOrEmpty(Reply)) { throw new NATSException("No Reply subject"); } diff --git a/src/NATS.Client/NATS.cs b/src/NATS.Client/NATS.cs index 5fe5c22da..31963f125 100644 --- a/src/NATS.Client/NATS.cs +++ b/src/NATS.Client/NATS.cs @@ -20,21 +20,21 @@ * * \section intro_sec Introduction * - * The %NATS .NET Client is part of %NATS an open-source, cloud-native + * The %NATS .NET Client is part of %NATS an open-source, cloud-native * messaging system. * This client, written in C#, follows the go client closely, but * diverges in places to follow the common design semantics of a .NET API. * * \section install_sec Installation - * + * * Instructions to build and install the %NATS .NET C# client can be * found at the [NATS .NET C# GitHub page](https://github.com/nats-io/csharp-nats) * * \section other_doc_section Other Documentation - * + * * This documentation focuses on the %NATS .NET C# Client API; for additional * information, refer to the following: - * + * * - [General Documentation for nats.io](https://nats-io.github.io/docs/) * - [NATS .NET C# Client found on GitHub](https://github.com/nats-io/nats.net) * - [The NATS server found on GitHub](https://github.com/nats-io/nats-server) @@ -210,7 +210,7 @@ public static EventHandler DefaultPullStatusErrorEventHandler() public static EventHandler DefaultFlowControlProcessedEventHandler() => (sender, e) => WriteJsEvent("FlowControlProcessed", e, "FcSubject: ", e?.FcSubject, "Source: ", e?.Source); - private static void WriteJsEvent(String label, ConnJsSubEventArgs e, params object[] pairs) { + private static void WriteJsEvent(string label, ConnJsSubEventArgs e, params object[] pairs) { var sb = BeginFormatMessage(label, e?.Conn, e?.Sub, null); if (e?.JetStreamSub != null && e?.JetStreamSub.Consumer != null) { @@ -223,7 +223,7 @@ private static void WriteJsEvent(String label, ConnJsSubEventArgs e, params obje Console.Out.WriteLine(sb.ToString()); } - private static void WriteEvent(String label, ConnEventArgs e) + private static void WriteEvent(string label, ConnEventArgs e) { if (e == null) Console.Out.WriteLine(label); @@ -233,7 +233,7 @@ private static void WriteEvent(String label, ConnEventArgs e) Console.Error.WriteLine(BeginFormatMessage(label, e.Conn, null, e.Error.Message).ToString()); } - private static void WriteError(String label, ErrEventArgs e) { + private static void WriteError(string label, ErrEventArgs e) { Console.Error.WriteLine(e == null ? label : BeginFormatMessage(label, e.Conn, e.Subscription, e.Error).ToString()); } diff --git a/src/NATS.Client/NKeys.cs b/src/NATS.Client/NKeys.cs index 79bdbd744..f83906d7d 100644 --- a/src/NATS.Client/NKeys.cs +++ b/src/NATS.Client/NKeys.cs @@ -353,7 +353,7 @@ public static NkeyPair FromPublicKey(char[] publicKey) } /// - /// Creates an NkeyPair from a private seed String. + /// Creates an NkeyPair from a private seed string. /// /// /// A NATS Ed25519 Keypair @@ -417,7 +417,7 @@ private static string CreateSeed(byte prefixbyte) } /// - /// Creates a private user seed String. + /// Creates a private user seed string. /// /// A NATS Ed25519 User Seed public static string CreateUserSeed() @@ -426,7 +426,7 @@ public static string CreateUserSeed() } /// - /// Creates a private account seed String. + /// Creates a private account seed string. /// /// A NATS Ed25519 Account Seed public static string CreateAccountSeed() @@ -435,7 +435,7 @@ public static string CreateAccountSeed() } /// - /// Creates a private operator seed String. + /// Creates a private operator seed string. /// /// A NATS Ed25519 Operator Seed public static string CreateOperatorSeed() diff --git a/src/NATS.Client/NUID.cs b/src/NATS.Client/NUID.cs index c16a0f527..434f7c16e 100644 --- a/src/NATS.Client/NUID.cs +++ b/src/NATS.Client/NUID.cs @@ -123,7 +123,7 @@ private string getNextNuid() b[i] = digits[(int)(l % nuidBase)]; } - return new String(b); + return new string(b); } private void resetSequential() diff --git a/src/NATS.Client/ObjectStore/IObjectStoreManagement.cs b/src/NATS.Client/ObjectStore/IObjectStoreManagement.cs index 9e91fe04e..0de2970f6 100644 --- a/src/NATS.Client/ObjectStore/IObjectStoreManagement.cs +++ b/src/NATS.Client/ObjectStore/IObjectStoreManagement.cs @@ -11,7 +11,6 @@ // See the License for the specific language governing permissions and // limitations under the License. -using System; using System.Collections.Generic; namespace NATS.Client.ObjectStore @@ -31,7 +30,7 @@ public interface IObjectStoreManagement /// OBJECT STORE IMPLEMENTATION IS EXPERIMENTAL AND SUBJECT TO CHANGE. /// /// list of object stores bucket names - IList GetBucketNames(); + IList GetBucketNames(); /// /// Gets the status for an existing object store. @@ -50,6 +49,6 @@ public interface IObjectStoreManagement /// Deletes an existing object store. Will throw a JetStreamApiException if the delete fails. /// OBJECT STORE IMPLEMENTATION IS EXPERIMENTAL AND SUBJECT TO CHANGE. /// - void Delete(String bucketName); + void Delete(string bucketName); } -} \ No newline at end of file +} diff --git a/src/NATS.Client/ObjectStore/ObjectInfo.cs b/src/NATS.Client/ObjectStore/ObjectInfo.cs index 4500f8cdc..10a07c097 100644 --- a/src/NATS.Client/ObjectStore/ObjectInfo.cs +++ b/src/NATS.Client/ObjectStore/ObjectInfo.cs @@ -113,11 +113,11 @@ public override int GetHashCode() } } - internal static ObjectInfoBuilder Builder(String bucket, String objectName) { + internal static ObjectInfoBuilder Builder(string bucket, string objectName) { return new ObjectInfoBuilder(bucket, objectName); } - internal static ObjectInfoBuilder Builder(String bucket, ObjectMeta meta) { + internal static ObjectInfoBuilder Builder(string bucket, ObjectMeta meta) { return new ObjectInfoBuilder(bucket, meta); } @@ -135,12 +135,12 @@ public sealed class ObjectInfoBuilder { internal bool _deleted; internal ObjectMeta.ObjectMetaBuilder _metaBuilder; - internal ObjectInfoBuilder(String bucket, String objectName) { + internal ObjectInfoBuilder(string bucket, string objectName) { _metaBuilder = ObjectMeta.Builder(objectName); WithBucket(bucket); } - public ObjectInfoBuilder(String bucket, ObjectMeta meta) { + public ObjectInfoBuilder(string bucket, ObjectMeta meta) { _metaBuilder = ObjectMeta.Builder(meta); WithBucket(bucket); } @@ -156,17 +156,17 @@ public ObjectInfoBuilder(ObjectInfo info) { _metaBuilder = ObjectMeta.Builder(info.ObjectMeta); } - public ObjectInfoBuilder WithObjectName(String name) { + public ObjectInfoBuilder WithObjectName(string name) { _metaBuilder.WithObjectName(name); return this; } - public ObjectInfoBuilder WithBucket(String bucket) { + public ObjectInfoBuilder WithBucket(string bucket) { this._bucket = Validator.ValidateBucketName(bucket, true); return this; } - public ObjectInfoBuilder WithNuid(String nuid) { + public ObjectInfoBuilder WithNuid(string nuid) { this._nuid = nuid; return this; } diff --git a/src/NATS.Client/ObjectStore/ObjectLink.cs b/src/NATS.Client/ObjectStore/ObjectLink.cs index 3b2434273..d2c91a253 100644 --- a/src/NATS.Client/ObjectStore/ObjectLink.cs +++ b/src/NATS.Client/ObjectStore/ObjectLink.cs @@ -11,7 +11,6 @@ // See the License for the specific language governing permissions and // limitations under the License. -using System; using NATS.Client.Internals; using NATS.Client.Internals.SimpleJSON; using NATS.Client.JetStream; @@ -26,8 +25,8 @@ public sealed class ObjectLink : JsonSerializable { public string Bucket { get; } public string ObjectName { get; } - public bool IsObjectLink => !String.IsNullOrEmpty(ObjectName); - public bool IsBucketLink => String.IsNullOrEmpty(ObjectName); + public bool IsObjectLink => !string.IsNullOrEmpty(ObjectName); + public bool IsBucketLink => string.IsNullOrEmpty(ObjectName); internal static ObjectLink OptionalInstance(JSONNode objectLinkNode) { diff --git a/src/NATS.Client/ObjectStore/ObjectStore.cs b/src/NATS.Client/ObjectStore/ObjectStore.cs index bb6ce13a7..c6b22d84d 100644 --- a/src/NATS.Client/ObjectStore/ObjectStore.cs +++ b/src/NATS.Client/ObjectStore/ObjectStore.cs @@ -14,8 +14,6 @@ using System; using System.Collections.Generic; using System.IO; -using System.Security.Cryptography; -using System.Text; using NATS.Client.Internals; using NATS.Client.JetStream; using static NATS.Client.ObjectStore.ObjectStoreUtil; @@ -89,8 +87,8 @@ public ObjectInfo Put(ObjectMeta meta, Stream inputStream) throw OsLinkNotAllowOnPut.Instance(); } - String nuid = Nuid.NextGlobal(); - String chunkSubject = PubSubChunkSubject(nuid); + string nuid = Nuid.NextGlobal(); + string chunkSubject = PubSubChunkSubject(nuid); int chunkSize = meta.ObjectMetaOptions.ChunkSize; if (chunkSize <= 0) { diff --git a/src/NATS.Client/Options.cs b/src/NATS.Client/Options.cs index 654502a76..5b8adde43 100644 --- a/src/NATS.Client/Options.cs +++ b/src/NATS.Client/Options.cs @@ -12,7 +12,6 @@ // limitations under the License. using System; -using System.Linq; using System.Net.Security; using System.Reflection; using System.Security.Cryptography.X509Certificates; @@ -726,7 +725,7 @@ public int SubscriptionBatchSize // TODO After connect adr is complete internal IServerProvider ServerProvider { get => serverProvider; set => serverProvider = value; } - private void appendEventHandler(StringBuilder sb, String name, Delegate eh) + private void appendEventHandler(StringBuilder sb, string name, Delegate eh) { if (eh != null) sb.AppendFormat("{0}={1};", name, eh.GetMethodInfo().Name); @@ -823,7 +822,7 @@ public void SetReconnectJitter(int jitter, int tlsJitter) /// Returns a string representation of the /// value of this Options instance. /// - /// String value of this instance. + /// string value of this instance. public override string ToString() { StringBuilder sb = new StringBuilder(); diff --git a/src/NATS.Client/Service/Discovery.cs b/src/NATS.Client/Service/Discovery.cs index b16326a65..417cb4e8d 100644 --- a/src/NATS.Client/Service/Discovery.cs +++ b/src/NATS.Client/Service/Discovery.cs @@ -6,7 +6,12 @@ namespace NATS.Client.Service { /// - /// SERVICE IS AN EXPERIMENTAL API SUBJECT TO CHANGE + /// Discovery is a utility class to help discover services by executing Ping, Info and Stats requests + /// You are required to provide a connection. + /// Optionally you can set 'maxTimeMillis' and 'maxResults'. When making a discovery request, + /// the discovery will wait until the first one of those thresholds is reached before returning the results. + /// 'maxTimeMillis' defaults to {@value DEFAULT_DISCOVERY_MAX_TIME_MILLIS} + /// 'maxResults' defaults tp {@value DEFAULT_DISCOVERY_MAX_RESULTS} /// public class Discovery { @@ -17,8 +22,12 @@ public class Discovery private readonly int maxTimeMillis; private readonly int maxResults; - private Func _inboxSupplier; - public Func InboxSupplier + private Func _inboxSupplier; + + /// + /// Override the normal inbox with a custom inbox to support you security model + /// + public Func InboxSupplier { get => _inboxSupplier; set @@ -27,7 +36,13 @@ public Func InboxSupplier } } - public Discovery(IConnection conn, int maxTimeMillis = -1, int maxResults = -1) + /// + /// Construct a Discovery instance + /// + /// the NATS Connection + /// optional, the maximum time to wait for discovery requests to complete or any number less than 1 to use the default + /// optional, the maximum number of results to wait for or any number less than 1 to use the default + public Discovery(IConnection conn, int maxTimeMillis = 0, int maxResults = 0) { this.conn = conn; this.maxTimeMillis = maxTimeMillis < 1 ? DefaultDiscoveryMaxTimeMillis : maxTimeMillis; @@ -38,7 +53,26 @@ public Discovery(IConnection conn, int maxTimeMillis = -1, int maxResults = -1) // ---------------------------------------------------------------------------------------------------- // ping // ---------------------------------------------------------------------------------------------------- - public IList Ping(string serviceName = null) + + /// + /// Make a ping request to all services running on the server. + /// + /// the list of + public IList Ping() + { + IList list = new List(); + DiscoverMany(Service.SrvPing, null, json => { + list.Add(new PingResponse(json)); + }); + return list; + } + + /// + /// Make a stats request only to services having the matching service name + /// + /// the service name + /// the list of + public IList Ping(string serviceName) { IList list = new List(); DiscoverMany(Service.SrvPing, serviceName, json => { @@ -47,6 +81,12 @@ public IList Ping(string serviceName = null) return list; } + /// + /// Make a ping request only to services having the matching service name + /// + /// the service name + /// the specific service id + /// the list of public PingResponse PingForNameAndId(string serviceName, string serviceId) { string json = DiscoverOne(Service.SrvPing, serviceName, serviceId); @@ -56,7 +96,26 @@ public PingResponse PingForNameAndId(string serviceName, string serviceId) // ---------------------------------------------------------------------------------------------------- // info // ---------------------------------------------------------------------------------------------------- - public IList Info(string serviceName = null) + + /// + /// Make an info request to all services running on the server. + /// + /// the list of + public IList Info() + { + IList list = new List(); + DiscoverMany(Service.SrvInfo, null, json => { + list.Add(new InfoResponse(json)); + }); + return list; + } + + /// + /// Make an info request only to services having the matching service name + /// + /// the service name + /// the list of + public IList Info(string serviceName) { IList list = new List(); DiscoverMany(Service.SrvInfo, serviceName, json => { @@ -65,7 +124,14 @@ public IList Info(string serviceName = null) return list; } - public InfoResponse InfoForNameAndId(string serviceName, string serviceId) { + /// + /// Make an info request to a specific instance of a service having matching service name and id + /// + /// the service name + /// the specific service id + /// the list of + public InfoResponse InfoForNameAndId(string serviceName, string serviceId) + { string json = DiscoverOne(Service.SrvInfo, serviceName, serviceId); return json == null ? null : new InfoResponse(json); } @@ -73,7 +139,26 @@ public InfoResponse InfoForNameAndId(string serviceName, string serviceId) { // ---------------------------------------------------------------------------------------------------- // stats // ---------------------------------------------------------------------------------------------------- - public IList Stats(string serviceName = null) + + /// + /// Make a stats request to all services running on the server. + /// + /// the list of + public IList Stats() + { + IList list = new List(); + DiscoverMany(Service.SrvStats, null, json => { + list.Add(new StatsResponse(json)); + }); + return list; + } + + /// + /// Make a stats request only to services having the matching service name + /// + /// the service name + /// the list of + public IList Stats(string serviceName) { IList list = new List(); DiscoverMany(Service.SrvStats, serviceName, json => { @@ -82,7 +167,14 @@ public IList Stats(string serviceName = null) return list; } - public StatsResponse StatsForNameAndId(string serviceName, string serviceId) { + /// + /// Make a stats request to a specific instance of a service having matching service name and id + /// + /// the service name + /// the specific service id + /// the list of + public StatsResponse StatsForNameAndId(string serviceName, string serviceId) + { string json = DiscoverOne(Service.SrvStats, serviceName, serviceId); return json == null ? null : new StatsResponse(json); } @@ -90,7 +182,8 @@ public StatsResponse StatsForNameAndId(string serviceName, string serviceId) { // ---------------------------------------------------------------------------------------------------- // workers // ---------------------------------------------------------------------------------------------------- - private string DiscoverOne(string action, string serviceName, string serviceId) { + private string DiscoverOne(string action, string serviceName, string serviceId) + { try { string subject = Service.ToDiscoverySubject(action, serviceName, serviceId); Msg m = conn.Request(subject, null, maxTimeMillis); @@ -100,7 +193,8 @@ private string DiscoverOne(string action, string serviceName, string serviceId) return null; } - private void DiscoverMany(string action, string serviceName, Action stringConsumer) { + private void DiscoverMany(string action, string serviceName, Action stringConsumer) + { ISyncSubscription sub = null; try { string replyTo = InboxSupplier.Invoke(); diff --git a/src/NATS.Client/Service/Endpoint.cs b/src/NATS.Client/Service/Endpoint.cs index a4d0f860a..5521bfb98 100644 --- a/src/NATS.Client/Service/Endpoint.cs +++ b/src/NATS.Client/Service/Endpoint.cs @@ -6,20 +6,53 @@ namespace NATS.Client.Service { /// - /// SERVICE IS AN EXPERIMENTAL API SUBJECT TO CHANGE + /// Endpoint encapsulates the name, subject and metadata for a . + /// Endpoints can be used directly or as part of a group. and + /// Endpoint names and subjects are considered 'Restricted Terms' and must only contain A-Z, a-z, 0-9, '-' or '_' + /// To create an Endpoint, either use a direct constructor or use the Endpoint builder + /// via the static method builder() or new Endpoint.Builder() to get an instance. + /// /// public class Endpoint : JsonSerializable { + private IDictionary _metadata; + + /// The name of the Endpoint public string Name { get; } + + /// The subject of the Endpoint public string Subject { get; } - public Dictionary Metadata { get; } + /// A copy of the metadata of the Endpoint + public IDictionary Metadata => + _metadata == null ? null : new Dictionary(_metadata); + + /// + /// Directly construct an Endpoint with a name, which becomes the subject + /// + /// the name public Endpoint(string name) : this(name, null, null, true) {} + /// + /// Directly construct an Endpoint with a name, which becomes the subject, and metadata + /// + /// the name + /// the metadata public Endpoint(string name, IDictionary metadata) : this(name, null, metadata, true) {} + /// + /// Directly construct an Endpoint with a name and a subject + /// + /// the name + /// the subject public Endpoint(string name, string subject) : this(name, subject, null, true) {} + /// + /// Directly construct an Endpoint with a name, the subject, and metadata + /// + /// the name + /// the subject + /// the metadata public Endpoint(string name, string subject, IDictionary metadata) : this(name, subject, metadata, true) {} // internal use constructors @@ -40,15 +73,11 @@ internal Endpoint(string name, string subject, IDictionary metad if (metadata == null || metadata.Count == 0) { - Metadata = null; + _metadata = null; } else { - Metadata = new Dictionary(); - foreach (var key in metadata.Keys) - { - Metadata[key] = metadata[key]; - } + _metadata = new Dictionary(metadata); } } @@ -56,62 +85,91 @@ internal Endpoint(JSONNode node) { Name = node[ApiConstants.Name]; Subject = node[ApiConstants.Subject]; - Metadata = JsonUtils.StringStringDictionary(node, ApiConstants.Metadata, true); + _metadata = JsonUtils.StringStringDictionary(node, ApiConstants.Metadata, true); } private Endpoint(EndpointBuilder b) - : this(b.Name, b.Subject, b.Metadata, true) {} + : this(b._name, b._subject, b._metadata, true) {} + /// + /// Build a service using a fluent builder. Use Service.Builder() to get an instance or new ServiceBuilder() + /// public override JSONNode ToJsonNode() { JSONObject jso = new JSONObject(); JsonUtils.AddField(jso, ApiConstants.Name, Name); JsonUtils.AddField(jso, ApiConstants.Subject, Subject); - JsonUtils.AddField(jso, ApiConstants.Metadata, Metadata); + JsonUtils.AddField(jso, ApiConstants.Metadata, _metadata); return jso; } + /// + /// Get an instance of an Endpoint builder. + /// + /// the instance public static EndpointBuilder Builder() => new EndpointBuilder(); + /// + /// Build an Endpoint using a fluent builder. + /// public sealed class EndpointBuilder { - internal string Name; - internal string Subject; - internal Dictionary Metadata; - - public EndpointBuilder WithEndpoint(Endpoint endpoint) { - Name = endpoint.Name; - Subject = endpoint.Subject; - return this; + internal string _name; + internal string _subject; + internal IDictionary _metadata; + + /// + /// Copy the Endpoint, replacing all existing endpoint information. + /// + /// the endpoint to copy + /// + public EndpointBuilder WithEndpoint(Endpoint endpoint) + { + return WithName(endpoint.Name).WithSubject(endpoint.Subject).WithMetadata(endpoint.Metadata); } + /// + /// Set the name for the Endpoint, replacing any name already set. + /// + /// the endpoint name + /// public EndpointBuilder WithName(string name) { - Name = name; + _name = name; return this; } + /// + /// Set the subject for the Endpoint, replacing any subject already set. + /// + /// the subject + /// public EndpointBuilder WithSubject(string subject) { - Subject = subject; + _subject = subject; return this; } + /// + /// Set the metadata for the Endpoint, replacing any metadata already set. + /// + /// the metadata + /// public EndpointBuilder WithMetadata(IDictionary metadata) { if (metadata == null || metadata.Count == 0) { - Metadata = null; + _metadata = null; } else { - Metadata = new Dictionary(); - foreach (var key in metadata.Keys) - { - Metadata[key] = metadata[key]; - } + _metadata = new Dictionary(metadata); } return this; } + /// + /// Build the Endpoint instance. + /// + /// the Endpoint instance public Endpoint Build() { return new Endpoint(this); } @@ -124,7 +182,7 @@ public override string ToString() protected bool Equals(Endpoint other) { - return Name == other.Name && Subject == other.Subject && Equals(Metadata, other.Metadata); + return Name == other.Name && Subject == other.Subject && Equals(_metadata, other._metadata); } public override bool Equals(object obj) @@ -141,7 +199,7 @@ public override int GetHashCode() { var hashCode = (Name != null ? Name.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (Subject != null ? Subject.GetHashCode() : 0); - hashCode = (hashCode * 397) ^ (Metadata != null ? Metadata.GetHashCode() : 0); + hashCode = (hashCode * 397) ^ (_metadata != null ? _metadata.GetHashCode() : 0); return hashCode; } } diff --git a/src/NATS.Client/Service/EndpointContext.cs b/src/NATS.Client/Service/EndpointContext.cs index 624f80216..79ad7a9fb 100644 --- a/src/NATS.Client/Service/EndpointContext.cs +++ b/src/NATS.Client/Service/EndpointContext.cs @@ -17,6 +17,9 @@ namespace NATS.Client.Service { + /// + /// Internal class to support service implementation + /// internal class EndpointContext { private const string QGroup = "q"; @@ -24,7 +27,7 @@ internal class EndpointContext private readonly IConnection conn; private ServiceEndpoint se; private readonly bool recordStats; - private readonly String qGroup; + private readonly string qGroup; internal IAsyncSubscription Sub { get; private set; } private DateTime started; @@ -88,8 +91,8 @@ internal void OnMessage(object sender, MsgHandlerEventArgs args) } } - internal EndpointResponse GetEndpointStats() { - return new EndpointResponse( + internal EndpointStats GetEndpointStats() { + return new EndpointStats( se.Endpoint.Name, se.Subject, numRequests.Read(), diff --git a/src/NATS.Client/Service/EndpointResponse.cs b/src/NATS.Client/Service/EndpointStats.cs similarity index 65% rename from src/NATS.Client/Service/EndpointResponse.cs rename to src/NATS.Client/Service/EndpointStats.cs index 818fc7ca8..2907d9143 100644 --- a/src/NATS.Client/Service/EndpointResponse.cs +++ b/src/NATS.Client/Service/EndpointStats.cs @@ -20,21 +20,79 @@ namespace NATS.Client.Service { /// - /// SERVICE IS AN EXPERIMENTAL API SUBJECT TO CHANGE + /// Endpoints stats contains various stats and custom data for an endpoint. + /// + /// { + /// "id": "ZP1oVevzLGu4CBORMXKKke", + /// "name": "Service1", + /// "version": "0.0.1", + /// "endpoints": [{ + /// "name": "SortEndpointAscending", + /// "subject": "sort.ascending", + /// "num_requests": 1, + /// "processing_time": 538900, + /// "average_processing_time": 538900, + /// "started": "2023-08-15T13:51:41.318000000Z" + /// } + /// + /// + /// { + /// "name": "SortEndpointDescending", + /// "subject": "sort.descending", + /// "num_requests": 1, + /// "processing_time": 88400, + /// "average_processing_time": 88400, + /// "started": "2023-08-15T13:51:41.318000000Z" + /// } + /// + /// + /// { + /// "name": "EchoEndpoint", + /// "subject": "echo", + /// "num_requests": 5, + /// "processing_time": 1931600, + /// "average_processing_time": 386320, + /// "data": { + /// "idata": 2, + /// "sdata": "s-996409223" + /// }, + /// "started": "2023-08-15T13:51:41.318000000Z" + /// } + /// /// - public class EndpointResponse : JsonSerializable + public class EndpointStats : JsonSerializable { + /// Get the name of the Endpoint public string Name { get; } + + /// Get the subject of the Endpoint public string Subject { get; } + + /// The number of requests received by the endpoint public long NumRequests { get; } + + /// Number of errors that the endpoint has raised public long NumErrors { get; } + + /// Total processing time for the endpoint public long ProcessingTime { get; } + + /// Average processing time is the total processing time divided by the num requests public long AverageProcessingTime { get; } + + /// If set, the last error triggered by the endpoint public string LastError { get; } + + /// A field that can be customized with any data as returned by stats handler public JSONNode Data { get; } + + /// The json representation of the custom data. May be null + public string DataAsJson => Data == null ? null : Data.ToString(); + + /// Get the time the endpoint was started (or restarted) public DateTime Started { get; } - internal EndpointResponse(string name, string subject, long numRequests, long numErrors, long processingTime, string lastError, JSONNode data, DateTime started) { + internal EndpointStats(string name, string subject, long numRequests, long numErrors, long processingTime, string lastError, JSONNode data, DateTime started) { Name = name; Subject = subject; NumRequests = numRequests; @@ -46,7 +104,7 @@ internal EndpointResponse(string name, string subject, long numRequests, long nu Started = started; } - internal EndpointResponse(string name, string subject) { + internal EndpointStats(string name, string subject) { Name = name; Subject = subject; NumRequests = 0; @@ -58,7 +116,7 @@ internal EndpointResponse(string name, string subject) { Started = DateTime.MinValue; } - internal EndpointResponse(JSONNode node) + internal EndpointStats(JSONNode node) { Name = node[ApiConstants.Name]; Subject = node[ApiConstants.Subject]; @@ -71,14 +129,14 @@ internal EndpointResponse(JSONNode node) Started = JsonUtils.AsDate(node[ApiConstants.Started]); } - internal static IList ListOf(JSONNode listNode) + internal static IList ListOf(JSONNode listNode) { - IList list = new List(); + IList list = new List(); if (listNode != null) { foreach (var esNode in listNode.Children) { - list.Add(new EndpointResponse(esNode)); + list.Add(new EndpointStats(esNode)); } } return list; @@ -104,7 +162,7 @@ public override string ToString() return JsonUtils.ToKey(GetType()) + ToJsonString(); } - protected bool Equals(EndpointResponse other) + protected bool Equals(EndpointStats other) { return Name == other.Name && Subject == other.Subject @@ -122,7 +180,7 @@ public override bool Equals(object obj) if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != this.GetType()) return false; - return Equals((EndpointResponse)obj); + return Equals((EndpointStats)obj); } public override int GetHashCode() diff --git a/src/NATS.Client/Service/Group.cs b/src/NATS.Client/Service/Group.cs index 1142f3418..f64b167df 100644 --- a/src/NATS.Client/Service/Group.cs +++ b/src/NATS.Client/Service/Group.cs @@ -16,20 +16,49 @@ namespace NATS.Client.Service { /// - /// SERVICE IS AN EXPERIMENTAL API SUBJECT TO CHANGE + /// Group is way to organize endpoints by serving as a common prefix to all endpoints registered in it. /// public class Group { private Group _next; + + /// Get the name of the group. public string Name { get; } + + /// Get the next group after this group. May be null. public Group Next => _next; + + /// The resolved subject of a group by concatenating the group name and any groups. + /// + /// For example, this: + /// + /// Group g = new Group("A") + /// .appendGroup(new Group("B")) + /// .appendGroup(new Group("C")) + /// .appendGroup(new Group("D")); + /// System.out.println(g.getSubject()); + /// + /// prints "A.B.C.D" + /// public string Subject => _next == null ? Name : $"{Name}.{_next.Subject}"; + /// + /// Construct a group. + ///

Group names and subjects are considered 'Restricted Terms' and must only contain A-Z, a-z, 0-9, '-' or '_'

+ ///
+ /// the group name public Group(string name) { Name = Validator.ValidateSubject(name, "Group Name", true, true); } + /// + /// Append a group at the end of the list of groups this group starts or is a part of. + /// Appended groups can be traversed by doing + /// Subsequent appends add the group to the end of the list. + /// + /// the group to append + /// like a fluent builder, return the Group instance public Group AppendGroup(Group group) { Group last = this; diff --git a/src/NATS.Client/Service/InfoResponse.cs b/src/NATS.Client/Service/InfoResponse.cs index e7a14d4e9..44f71baf8 100644 --- a/src/NATS.Client/Service/InfoResponse.cs +++ b/src/NATS.Client/Service/InfoResponse.cs @@ -19,13 +19,17 @@ namespace NATS.Client.Service { /// - /// SERVICE IS AN EXPERIMENTAL API SUBJECT TO CHANGE + /// Info response class forms the info json payload, for example: + /// {"id":"JlkwZvmHAXCQGwwxiPwaBJ","name":"MyService","version":"0.0.1","endpoints":[{"name":"MyEndpoint","subject":"myend"}],"type":"io.nats.micro.v1.info_response"} /// public class InfoResponse : ServiceResponse { public const string ResponseType = "io.nats.micro.v1.info_response"; + /// Description for the service public string Description { get; } + + /// List of endpoints public IList Endpoints { get; } public InfoResponse(string id, string name, string version, IDictionary metadata, string description, IList endpoints) diff --git a/src/NATS.Client/Service/PingResponse.cs b/src/NATS.Client/Service/PingResponse.cs index c068d028b..cd7a41d93 100644 --- a/src/NATS.Client/Service/PingResponse.cs +++ b/src/NATS.Client/Service/PingResponse.cs @@ -17,7 +17,8 @@ namespace NATS.Client.Service { /// - /// SERVICE IS AN EXPERIMENTAL API SUBJECT TO CHANGE + /// Ping response class forms the ping json payload, for example: + /// {"id":"JlkwZvmHAXCQGwwxiPwaBJ","name":"MyService","version":"0.0.1","type":"io.nats.micro.v1.ping_response"} /// public class PingResponse : ServiceResponse { diff --git a/src/NATS.Client/Service/Service.cs b/src/NATS.Client/Service/Service.cs index e23daeff9..031e70870 100644 --- a/src/NATS.Client/Service/Service.cs +++ b/src/NATS.Client/Service/Service.cs @@ -22,8 +22,9 @@ namespace NATS.Client.Service { /// /// The Services Framework introduces a higher-level API for implementing services with NATS. - /// Simply put, services are endpoint listeners that respond to a subject to provide a remote response to a question. - /// When multiple instances of endpoints are active they work in a queue, meaning only one listener responds. + /// Services automatically contain Ping, Info and Stats responders. + /// Services have one or more service endpoints. . + /// When multiple instances of a service endpoints are active they work in a queue, meaning only one listener responds to any given request. /// public class Service { @@ -35,10 +36,17 @@ public class Service private readonly IConnection conn; public int DrainTimeoutMillis { get; } - private readonly Dictionary serviceContexts; + private readonly IDictionary serviceContexts; private readonly IList discoveryContexts; + /// + /// The pre-constructed ping response. + /// public PingResponse PingResponse { get; } + + /// + /// The pre-constructed info response. + /// public InfoResponse InfoResponse { get; } private readonly Object startStopLock; @@ -118,6 +126,10 @@ internal static string ToDiscoverySubject(string discoverySubject, string servic return DefaultServicePrefix + discoverySubject + "." + serviceName + "." + serviceId; } + /// + /// Start the service + /// + /// a task that can be held to see if another thread called stop public Task StartService() { lock (startStopLock) @@ -139,16 +151,48 @@ public Task StartService() } } - public static ServiceBuilder Builder() { + /// + /// Get an instance of a ServiceBuilder. + /// + /// the instance + public static ServiceBuilder Builder() + { return new ServiceBuilder(); } - public void Stop(Exception e) + /// + /// Stop the service by draining. + /// + public void Stop() + { + Stop(true, null); + } + + /// + /// Stop the service by draining. Mark the task that was received from the start method that the service had an exception. + /// + /// the error cause + public void Stop(Exception e) { Stop(true, e); } - - public void Stop(bool drain = true, Exception e = null) { + + /// + /// Stop the service, optionally draining. + /// + /// the flag indicating to drain or not + public void Stop(bool drain) + { + Stop(drain, null); + } + + /// + /// Stop the service, optionally draining and optionally with an error cause + /// + /// the flag indicating to drain or not + /// the optional error cause. If supplied, mark the task that was received from the start method that the service had an exception. + public void Stop(bool drain, Exception e) + { lock (startStopLock) { if (runningIndicator != null) { if (drain) @@ -197,15 +241,26 @@ public void Reset() c.Reset(); } } - + + /// The id of the service public string Id => InfoResponse.Id; + + /// The name of the service public string Name => InfoResponse.Name; + + /// The version of the service public string Version => InfoResponse.Version; + + /// The description of the service public string Description => InfoResponse.Description; + /// + /// Get the up-to-date stats response which contains a list of all + /// + /// the stats response public StatsResponse GetStatsResponse() { - IList endpointStatsList = new List(); + IList endpointStatsList = new List(); foreach (EndpointContext c in serviceContexts.Values) { endpointStatsList.Add(c.GetEndpointStats()); @@ -213,7 +268,12 @@ public StatsResponse GetStatsResponse() return new StatsResponse(PingResponse, started, endpointStatsList); } - public EndpointResponse GetEndpointStats(string endpointName) + /// + /// Get the up-to-date for a specific endpoint + /// + /// the endpoint name + /// the EndpointStats or null if the name is not found + public EndpointStats GetEndpointStats(string endpointName) { EndpointContext c; if (serviceContexts.TryGetValue(endpointName, out c)) diff --git a/src/NATS.Client/Service/ServiceBuilder.cs b/src/NATS.Client/Service/ServiceBuilder.cs index 1664c64fb..42d883cb1 100644 --- a/src/NATS.Client/Service/ServiceBuilder.cs +++ b/src/NATS.Client/Service/ServiceBuilder.cs @@ -17,7 +17,7 @@ namespace NATS.Client.Service { /// - /// Used to build a service + /// Build a service using a fluent builder. Use Service.Builder() to get an instance or new ServiceBuilder() /// public class ServiceBuilder { @@ -27,58 +27,90 @@ public class ServiceBuilder internal string Name; internal string Description; internal string Version; - internal string ApiUrl; - internal readonly Dictionary ServiceEndpoints = new Dictionary(); + internal readonly IDictionary ServiceEndpoints = new Dictionary(); internal int DrainTimeoutMillis = DefaultDrainTimeoutMillis; - internal Dictionary Metadata; + internal IDictionary Metadata; + /// + /// The connection the service runs on + /// + /// connection + /// the ServiceBuilder public ServiceBuilder WithConnection(IConnection conn) { Conn = conn; return this; } + /// + /// The simple name of the service + /// + /// the name + /// the ServiceBuilder public ServiceBuilder WithName(string name) { Name = ValidateIsRestrictedTerm(name, "Service Name", true); return this; } + /// + /// The simple description of the service + /// + /// the description + /// the ServiceBuilder public ServiceBuilder WithDescription(string description) { Description = description; return this; } + /// + /// The simple version of the service. + /// + /// the version + /// the ServiceBuilder public ServiceBuilder WithVersion(string version) { Version = ValidateSemVer(version, "Service Version", true); return this; } - public ServiceBuilder WithMetadata(Dictionary metadata) + /// + /// Any meta information about this service + /// + /// the meta + /// the ServiceBuilder + public ServiceBuilder WithMetadata(IDictionary metadata) { Metadata = metadata; return this; } - public ServiceBuilder WithApiUrl(string apiUrl) - { - ApiUrl = apiUrl; - return this; - } - - public ServiceBuilder AddServiceEndpoint(ServiceEndpoint endpoint) { - ServiceEndpoints[endpoint.Name] = endpoint; + /// + /// Add a service endpoint into the service. There can only be one instance of an endpoint by name + /// + /// the endpoint + /// the ServiceBuilder + public ServiceBuilder AddServiceEndpoint(ServiceEndpoint serviceEndpoint) { + ServiceEndpoints[serviceEndpoint.Name] = serviceEndpoint; return this; } + /// + /// The timeout when stopping a service. Defaults to 5000 milliseconds + /// + /// the drain timeout in milliseconds + /// the ServiceBuilder public ServiceBuilder WithDrainTimeoutMillis(int drainTimeoutMillis) { DrainTimeoutMillis = drainTimeoutMillis; return this; } + /// + /// Build the Service instance + /// + /// the Service instance public Service Build() { Required(Conn, "Connection"); Required(Name, "Name"); diff --git a/src/NATS.Client/Service/ServiceEndpoint.cs b/src/NATS.Client/Service/ServiceEndpoint.cs index ed3dfd18e..707b87e87 100644 --- a/src/NATS.Client/Service/ServiceEndpoint.cs +++ b/src/NATS.Client/Service/ServiceEndpoint.cs @@ -12,13 +12,29 @@ // limitations under the License. using System; +using System.Collections.Generic; using NATS.Client.Internals; using NATS.Client.Internals.SimpleJSON; namespace NATS.Client.Service { /// - /// SERVICE IS AN EXPERIMENTAL API SUBJECT TO CHANGE + /// The ServiceEndpoint represents the working + /// + /// + /// It allows the endpoint to be grouped. + /// + /// + /// It is where you can define the handler that will respond to incoming requests + /// + /// + /// It allows you to define it's dispatcher if desired giving granularity to threads running subscribers + /// + /// + /// It gives you a hook to provide custom data for the + /// + /// + /// To create a ServiceEndpoint, use the ServiceEndpoint static method builder() or new ServiceEndpoint.Builder() to get an instance. /// public class ServiceEndpoint { @@ -26,10 +42,20 @@ public class ServiceEndpoint internal EventHandler Handler { get; } internal Func StatsDataSupplier { get; } internal Endpoint Endpoint { get; } - internal string Name => Endpoint.Name; - internal string Subject => Group == null ? Endpoint.Subject : $"{Group.Subject}.{Endpoint.Subject}"; + + /// The name of the + public string Name => Endpoint.Name; + + /// The subject of the ServiceEndpoint which takes into account the group path and the subject + public string Subject => Group == null ? Endpoint.Subject : $"{Group.Subject}.{Endpoint.Subject}"; - public ServiceEndpoint(ServiceEndpointBuilder b, Endpoint e) + /// A copy of the metadata of the + public IDictionary Metadata => Endpoint.Metadata == null ? null : new Dictionary(Endpoint.Metadata); + + /// The name for this ServiceEndpoint, or null if there is no group + public string GroupName => Group == null ? null : Group.Name; + + internal ServiceEndpoint(ServiceEndpointBuilder b, Endpoint e) { Group = b.Group; Endpoint = e; @@ -44,46 +70,97 @@ internal ServiceEndpoint(Endpoint endpoint, EventHandler + /// Get an instance of a ServiceEndpointBuilder. + /// + /// the instance public static ServiceEndpointBuilder Builder() { return new ServiceEndpointBuilder(); } - + + /// + /// Build a ServiceEndpoint using a fluent builder. + /// public sealed class ServiceEndpointBuilder { internal Group Group; internal EventHandler Handler; internal Func StatsDataSupplier; internal readonly Endpoint.EndpointBuilder EndpointBuilder = Endpoint.Builder(); + /// + /// Set the for this ServiceEndpoint + /// + /// The group + /// the ServiceEndpointBuilder public ServiceEndpointBuilder WithGroup(Group group) { Group = group; return this; } + /// + /// Set the for this ServiceEndpoint replacing all existing endpoint information. + /// + /// + /// the ServiceEndpointBuilder public ServiceEndpointBuilder WithEndpoint(Endpoint endpoint) { EndpointBuilder.WithEndpoint(endpoint); return this; } - public ServiceEndpointBuilder WithEndpointName(String name) { + /// + /// Set the name for the for this ServiceEndpoint replacing any name already set. + /// + /// + /// the ServiceEndpointBuilder + public ServiceEndpointBuilder WithEndpointName(string name) { EndpointBuilder.WithName(name); return this; } - public ServiceEndpointBuilder WithEndpointSubject(String subject) { + /// + /// Set the subject for the for this ServiceEndpoint replacing any subject already set. + /// + /// + /// the ServiceEndpointBuilder + public ServiceEndpointBuilder WithEndpointSubject(string subject) { EndpointBuilder.WithSubject(subject); return this; } + /// + /// Set the metadata for the for this ServiceEndpoint replacing any metadata already set. + /// + /// the metadata + /// the ServiceEndpointBuilder + public ServiceEndpointBuilder WithEndpointMetadata(IDictionary metadata) { + EndpointBuilder.WithMetadata(metadata); + return this; + } + + /// + /// Set the Service Message Handler for this ServiceEndpoint + /// + /// + /// the ServiceEndpointBuilder public ServiceEndpointBuilder WithHandler(EventHandler handler) { Handler = handler; return this; } + /// + /// Set the data supplier for this ServiceEndpoint + /// + /// the data supplier + /// the ServiceEndpointBuilder public ServiceEndpointBuilder WithStatsDataSupplier(Func statsDataSupplier) { StatsDataSupplier = statsDataSupplier; return this; } + /// + /// Build the ServiceEndpoint instance. + /// + /// the ServiceEndpoint instance public ServiceEndpoint Build() { Endpoint endpoint = EndpointBuilder.Build(); Validator.Required(Handler, "Message Handler"); diff --git a/src/NATS.Client/Service/ServiceException.cs b/src/NATS.Client/Service/ServiceException.cs index d43936238..be4bcc1a6 100644 --- a/src/NATS.Client/Service/ServiceException.cs +++ b/src/NATS.Client/Service/ServiceException.cs @@ -16,17 +16,18 @@ namespace NATS.Client.Service { /// - /// SERVICE IS AN EXPERIMENTAL API SUBJECT TO CHANGE + /// Exception specific to Service /// public class ServiceException : Exception { + /// The exception code public int Code { get; } - - public ServiceException(string message, int code = -1) : base(message) { + + internal ServiceException(string message, int code = -1) : base(message) { Code = code; } - public static ServiceException GetInstance(Exception e) + internal static ServiceException GetInstance(Exception e) { if (e is ServiceException se) { diff --git a/src/NATS.Client/Service/ServiceMsg.cs b/src/NATS.Client/Service/ServiceMsg.cs index d659b63b7..ef98724e8 100644 --- a/src/NATS.Client/Service/ServiceMsg.cs +++ b/src/NATS.Client/Service/ServiceMsg.cs @@ -18,55 +18,138 @@ namespace NATS.Client.Service { /// - /// SERVICE IS AN EXPERIMENTAL API SUBJECT TO CHANGE + /// Service Message is service specific object that exposes the service relevant parts of a NATS Message. /// - public class ServiceMsg : Msg + public class ServiceMsg { + /// + /// Standard header name used to report the text of an error + /// public const string NatsServiceError = "Nats-Service-Error"; + + /// + /// Standard header name used to report the code of an error + /// public const string NatsServiceErrorCode = "Nats-Service-Error-Code"; + + private readonly Msg msg; - internal ServiceMsg(Msg msg) : base(msg) {} + /// The subject that this message was sent to. + public string Subject => msg.Subject; - public void Respond(IConnection conn, byte[] response) { - conn.Publish(new Msg(_reply, null, null, response)); + /// The subject the application is expected to send a reply message on. + public string Reply => msg.Reply; + + /// Whether there are headers. + public bool HasHeaders => msg.HasHeaders; + + /// The headers object for the message. + public MsgHeader Header => msg.Header; + + /// The data from the message. + public byte[] Data => msg.Data; + + internal ServiceMsg(Msg msg) + { + this.msg = msg; + } + + /// + /// Respond to a service request message. + /// + /// the NATS connection + /// the response payload in the form of a byte array + public void Respond(IConnection conn, byte[] response) + { + conn.Publish(new Msg(msg.Reply, null, null, response)); } - public void Respond(IConnection conn, string response) { - conn.Publish(new Msg(_reply, null, null, Encoding.UTF8.GetBytes(response))); + /// + /// Respond to a service request message. + /// + /// the NATS connection + /// the response payload in the form of a string + public void Respond(IConnection conn, string response) + { + conn.Publish(new Msg(msg.Reply, null, null, Encoding.UTF8.GetBytes(response))); } - public void Respond(IConnection conn, JsonSerializable response) { - conn.Publish(new Msg(_reply, null, null, response.Serialize())); + /// + /// Respond to a service request message. + /// + /// the NATS connection + /// the response payload in the form of a object + public void Respond(IConnection conn, JsonSerializable response) + { + conn.Publish(new Msg(msg.Reply, null, null, response.Serialize())); } - public void Respond(IConnection conn, JSONNode response) { - conn.Publish(new Msg(_reply, null, null, Encoding.UTF8.GetBytes(response.ToString()))); + /// + /// Respond to a service request message. + /// + /// the NATS connection + /// the response payload in the form of a object + public void Respond(IConnection conn, JSONNode response) + { + conn.Publish(new Msg(msg.Reply, null, null, Encoding.UTF8.GetBytes(response.ToString()))); } + /// + /// Respond to a service request message with a response and custom headers. + /// + /// the NATS connection + /// the response payload in the form of a byte array + /// the custom headers public void Respond(IConnection conn, byte[] response, MsgHeader headers) { - conn.Publish(new Msg(_reply, null, headers, response)); + conn.Publish(new Msg(msg.Reply, null, headers, response)); } + /// + /// Respond to a service request message with a response and custom headers. + /// + /// the NATS connection + /// the response payload in the form of a string + /// the custom headers public void Respond(IConnection conn, string response, MsgHeader headers) { - conn.Publish(new Msg(_reply, null, headers, Encoding.UTF8.GetBytes(response))); + conn.Publish(new Msg(msg.Reply, null, headers, Encoding.UTF8.GetBytes(response))); } - public void Respond(IConnection conn, JsonSerializable response, MsgHeader headers) { - conn.Publish(new Msg(_reply, null, headers, response.Serialize())); + /// + /// Respond to a service request message. + /// + /// the NATS connection + /// the response payload in the form of a object + /// the custom headers + public void Respond(IConnection conn, JsonSerializable response, MsgHeader headers) + { + conn.Publish(new Msg(msg.Reply, null, headers, response.Serialize())); } - public void Respond(IConnection conn, JSONNode response, MsgHeader headers) { - conn.Publish(new Msg(_reply, null, headers, Encoding.UTF8.GetBytes(response.ToString()))); + /// + /// Respond to a service request message. + /// + /// the NATS connection + /// the response payload in the form of a object + /// the custom headers + public void Respond(IConnection conn, JSONNode response, MsgHeader headers) + { + conn.Publish(new Msg(msg.Reply, null, headers, Encoding.UTF8.GetBytes(response.ToString()))); } - public void RespondStandardError(IConnection conn, string errorMessage, int errorCode) + /// + /// Respond to a service request message with a standard error. + /// + /// the NATS connection + /// the error message text + /// the error message code + public void RespondStandardError(IConnection conn, string errorText, int errorCode) { - conn.Publish(new Msg(_reply, null, + conn.Publish(new Msg(msg.Reply, null, new MsgHeader { - [NatsServiceError] = errorMessage, + [NatsServiceError] = errorText, [NatsServiceErrorCode] = $"{errorCode}" }, null)); diff --git a/src/NATS.Client/Service/ServiceMsgHandlerEventArgs.cs b/src/NATS.Client/Service/ServiceMsgHandlerEventArgs.cs index 8c1129468..29a944179 100644 --- a/src/NATS.Client/Service/ServiceMsgHandlerEventArgs.cs +++ b/src/NATS.Client/Service/ServiceMsgHandlerEventArgs.cs @@ -16,7 +16,7 @@ namespace NATS.Client.Service { /// - /// SERVICE IS AN EXPERIMENTAL API SUBJECT TO CHANGE + /// Event handler used to receive service request message. /// public class ServiceMsgHandlerEventArgs : EventArgs { diff --git a/src/NATS.Client/Service/ServiceResponse.cs b/src/NATS.Client/Service/ServiceResponse.cs index 7607f214f..096156581 100644 --- a/src/NATS.Client/Service/ServiceResponse.cs +++ b/src/NATS.Client/Service/ServiceResponse.cs @@ -7,15 +7,27 @@ namespace NATS.Client.Service { /// - /// SERVICE IS AN EXPERIMENTAL API SUBJECT TO CHANGE + /// Base class for service responses Info, Ping and Stats /// public abstract class ServiceResponse : JsonSerializable { + internal IDictionary _metadata; + + /// The type of this response public string Type { get; } + + /// The unique ID of the service public string Id { get; } + + /// The name of the service public string Name { get; } + + /// The version of the service public string Version { get; } - public Dictionary Metadata { get; } + + /// A copy of the metadata for the service, or null if there is no metadata + public IDictionary Metadata => + _metadata == null ? null : new Dictionary(_metadata); internal ServiceResponse(string type, string id, string name, string version, IDictionary metadata) { @@ -25,26 +37,16 @@ internal ServiceResponse(string type, string id, string name, string version, ID Version = version; if (metadata == null || metadata.Count == 0) { - Metadata = null; + _metadata = null; } else { - Metadata = new Dictionary(); - foreach (var key in metadata.Keys) - { - Metadata[key] = metadata[key]; - } + _metadata = new Dictionary(metadata); } } - + internal ServiceResponse(string type, ServiceResponse template) - { - Type = type; - Id = template.Id; - Name = template.Name; - Version = template.Version; - Metadata = template.Metadata; - } + : this(type, template.Id, template.Name, template.Version, template._metadata) {} internal ServiceResponse(string type, JSONNode node) { @@ -59,7 +61,7 @@ internal ServiceResponse(string type, JSONNode node) Id = Validator.Required(node[ApiConstants.Id], "Id"); Name = Validator.Required(node[ApiConstants.Name], "Name"); Version = Validator.ValidateSemVer(node[ApiConstants.Version], "Version", true); - Metadata = JsonUtils.StringStringDictionary(node, ApiConstants.Metadata); + _metadata = JsonUtils.StringStringDictionary(node, ApiConstants.Metadata); } protected JSONObject BaseJsonObject() @@ -69,7 +71,7 @@ protected JSONObject BaseJsonObject() JsonUtils.AddField(jso, ApiConstants.Name, Name); JsonUtils.AddField(jso, ApiConstants.Type, Type); JsonUtils.AddField(jso, ApiConstants.Version, Version); - JsonUtils.AddField(jso, ApiConstants.Metadata, Metadata); + JsonUtils.AddField(jso, ApiConstants.Metadata, _metadata); return jso; } diff --git a/src/NATS.Client/Service/StatsResponse.cs b/src/NATS.Client/Service/StatsResponse.cs index 4f5b5d747..6a2c95482 100644 --- a/src/NATS.Client/Service/StatsResponse.cs +++ b/src/NATS.Client/Service/StatsResponse.cs @@ -20,16 +20,54 @@ namespace NATS.Client.Service { /// - /// SERVICE IS AN EXPERIMENTAL API SUBJECT TO CHANGE + /// Stats response class forms the stats json payload, for example: + /// + /// { + /// "id": "ZP1oVevzLGu4CBORMXKKke", + /// "name": "Service1", + /// "version": "0.0.1", + /// "endpoints": [{ + /// "name": "SortEndpointAscending", + /// "subject": "sort.ascending", + /// "num_requests": 1, + /// "processing_time": 538900, + /// "average_processing_time": 538900, + /// "started": "2023-08-15T13:51:41.318000000Z" + /// }, { + /// "name": "SortEndpointDescending", + /// "subject": "sort.descending", + /// "num_requests": 1, + /// "processing_time": 88400, + /// "average_processing_time": 88400, + /// "started": "2023-08-15T13:51:41.318000000Z" + /// }, { + /// "name": "EchoEndpoint", + /// "subject": "echo", + /// "num_requests": 5, + /// "processing_time": 1931600, + /// "average_processing_time": 386320, + /// "data": { + /// "idata": 2, + /// "sdata": "s-996409223" + /// }, + /// "started": "2023-08-15T13:51:41.318000000Z" + /// }], + /// "started": "2023-08-15T13:51:41.319000000Z", + /// "type": "io.nats.micro.v1.stats_response" + /// } + /// /// public class StatsResponse : ServiceResponse { public const string ResponseType = "io.nats.micro.v1.stats_response"; + /// The time the endpoint was started (or restarted) public DateTime Started { get; } - public IList EndpointStatsList { get; } - internal StatsResponse(ServiceResponse template, DateTime started, IList endpointStatsList) + /// Get the list of + public IList EndpointStatsList { get; } + + internal StatsResponse(ServiceResponse template, DateTime started, IList endpointStatsList) :base(ResponseType, template) { Started = started; @@ -41,7 +79,7 @@ internal StatsResponse(string json) : this(JSON.Parse(json)) {} internal StatsResponse(JSONNode node) : base(ResponseType, node) { Started = JsonUtils.AsDate(node[ApiConstants.Started]); - EndpointStatsList = EndpointResponse.ListOf(node[ApiConstants.Endpoints]); + EndpointStatsList = EndpointStats.ListOf(node[ApiConstants.Endpoints]); } public override JSONNode ToJsonNode() diff --git a/src/NATS.Client/Subscription.cs b/src/NATS.Client/Subscription.cs index 7e86a2928..944108396 100644 --- a/src/NATS.Client/Subscription.cs +++ b/src/NATS.Client/Subscription.cs @@ -148,7 +148,7 @@ internal void close(bool closeChannel) public string Queue => queue; internal string SubName() => subject + "(" + sid + ")" + - (String.IsNullOrWhiteSpace(queue) ? "" : " (queue: " + queue + ")"); + (string.IsNullOrWhiteSpace(queue) ? "" : " (queue: " + queue + ")"); /// diff --git a/src/Samples/JetStreamExampleUtils/JsUtils.cs b/src/Samples/JetStreamExampleUtils/JsUtils.cs index 3cf623c7f..35b8886cb 100644 --- a/src/Samples/JetStreamExampleUtils/JsUtils.cs +++ b/src/Samples/JetStreamExampleUtils/JsUtils.cs @@ -191,7 +191,7 @@ public static StreamInfo CreateStreamOrUpdateSubjects(IConnection c, string stre subjects); } - public static void CreateOrReplaceStream(IJetStreamManagement jsm, String stream, String subject) + public static void CreateOrReplaceStream(IJetStreamManagement jsm, string stream, string subject) { // in case the stream was here before, we want a completely new one try @@ -217,12 +217,12 @@ public static void Publish(IConnection c, string subject, int count) Publish(c.CreateJetStreamContext(), subject, "data", count, false); } - public static void Publish(IJetStream js, String subject, int count) + public static void Publish(IJetStream js, string subject, int count) { Publish(js, subject, "data", count, false); } - public static void Publish(IJetStream js, String subject, String prefix, int count, bool verbose = true) + public static void Publish(IJetStream js, string subject, string prefix, int count, bool verbose = true) { if (verbose) { @@ -231,7 +231,7 @@ public static void Publish(IJetStream js, String subject, String prefix, int cou for (int x = 1; x <= count; x++) { - String data = prefix + x; + string data = prefix + x; if (verbose) { Console.Write(" " + data); @@ -246,7 +246,7 @@ public static void Publish(IJetStream js, String subject, String prefix, int cou } } - public static void PublishInBackground(IJetStream js, String subject, String prefix, int count) + public static void PublishInBackground(IJetStream js, string subject, string prefix, int count) { new Thread(() => { diff --git a/src/Samples/JetStreamManageStreams/JetStreamManageStreams.cs b/src/Samples/JetStreamManageStreams/JetStreamManageStreams.cs index 37f462f3d..775108e09 100644 --- a/src/Samples/JetStreamManageStreams/JetStreamManageStreams.cs +++ b/src/Samples/JetStreamManageStreams/JetStreamManageStreams.cs @@ -107,7 +107,7 @@ public static void Main(string[] args) PrintUtils.PrintStreamInfo(streamInfo); Console.WriteLine("----------\n4.2 getStreamNames"); - IList streamNames = jsm.GetStreamNames(); + IList streamNames = jsm.GetStreamNames(); PrintUtils.PrintObject(streamNames); Console.WriteLine("----------\n4.3 getStreams"); diff --git a/src/Samples/KeyValueFull/KeyValueFull.cs b/src/Samples/KeyValueFull/KeyValueFull.cs index 0b75d81dd..413402883 100644 --- a/src/Samples/KeyValueFull/KeyValueFull.cs +++ b/src/Samples/KeyValueFull/KeyValueFull.cs @@ -87,7 +87,7 @@ public static void Main(string[] args) // as a UTF-8 string, the ValueAsString function is ok to use Console.WriteLine("\n3. Get String Value"); - String svalue = kv.Get(ByteKey).ValueAsString(); + string svalue = kv.Get(ByteKey).ValueAsString(); Console.WriteLine(ByteKey + " from ValueAsString(): " + svalue); svalue = kv.Get(StringKey).ValueAsString(); diff --git a/src/Samples/ServiceExample/ServiceExample.cs b/src/Samples/ServiceExample/ServiceExample.cs index 15e407252..38e3d3ff2 100644 --- a/src/Samples/ServiceExample/ServiceExample.cs +++ b/src/Samples/ServiceExample/ServiceExample.cs @@ -76,7 +76,6 @@ public static void Main(string[] args) Service service1 = new ServiceBuilder() .WithConnection(c) .WithName("Service1") - .WithApiUrl("Service1 Api Url") // optional .WithDescription("Service1 Description") // optional .WithVersion("0.0.1") .AddServiceEndpoint(seEcho1) @@ -180,7 +179,7 @@ public static void Main(string[] args) } } - private static string ReplyBody(String label, byte[] data, String handlerId) + private static string ReplyBody(string label, byte[] data, string handlerId) { JSONObject o = new JSONObject(); o[label] = Encoding.UTF8.GetString(data); @@ -188,7 +187,7 @@ private static string ReplyBody(String label, byte[] data, String handlerId) return o.ToString(); } - private static void HandlerSortDescending(IConnection nc, ServiceMsg smsg, String handlerId) { + private static void HandlerSortDescending(IConnection nc, ServiceMsg smsg, string handlerId) { Array.Sort(smsg.Data); int len = smsg.Data.Length; byte[] descending = new byte[len]; @@ -198,12 +197,12 @@ private static void HandlerSortDescending(IConnection nc, ServiceMsg smsg, Strin smsg.Respond(nc, ReplyBody("sort_descending", descending, handlerId)); } - private static void HandleSortAscending(IConnection nc, ServiceMsg smsg, String handlerId) { + private static void HandleSortAscending(IConnection nc, ServiceMsg smsg, string handlerId) { Array.Sort(smsg.Data); smsg.Respond(nc, ReplyBody("sort_ascending", smsg.Data, handlerId)); } - private static void HandleEchoMessage(IConnection nc, ServiceMsg smsg, String handlerId) { + private static void HandleEchoMessage(IConnection nc, ServiceMsg smsg, string handlerId) { smsg.Respond(nc, ReplyBody("echo", smsg.Data, handlerId)); } @@ -269,7 +268,7 @@ class ExampleStatsData : JsonSerializable public readonly string SData; public readonly int IData; - public ExampleStatsData(String sData, int iData) + public ExampleStatsData(string sData, int iData) { SData = sData; IData = iData; diff --git a/src/Samples/SimplificationFetchBytes/FetchBytesExample.cs b/src/Samples/SimplificationFetchBytes/FetchBytesExample.cs index 3ca40d027..3d8b6f312 100644 --- a/src/Samples/SimplificationFetchBytes/FetchBytesExample.cs +++ b/src/Samples/SimplificationFetchBytes/FetchBytesExample.cs @@ -28,7 +28,7 @@ internal static class FetchBytesExample private static readonly int EXPIRES_SECONDS = 2; public static string SERVER = "nats://localhost:4222"; - public static void Main(String[] args) + public static void Main(string[] args) { Options opts = ConnectionFactory.GetDefaultOptions(SERVER); diff --git a/src/Samples/SimplificationFetchMessages/FetchMessagesExample.cs b/src/Samples/SimplificationFetchMessages/FetchMessagesExample.cs index a58d24ff1..e06579cf4 100644 --- a/src/Samples/SimplificationFetchMessages/FetchMessagesExample.cs +++ b/src/Samples/SimplificationFetchMessages/FetchMessagesExample.cs @@ -29,7 +29,7 @@ internal static class FetchMessagesExample public static string SERVER = "nats://localhost:4222"; - public static void Main(String[] args) + public static void Main(string[] args) { Options opts = ConnectionFactory.GetDefaultOptions(SERVER); diff --git a/src/Samples/SimplificationIterableConsumer/IterableConsumerExample.cs b/src/Samples/SimplificationIterableConsumer/IterableConsumerExample.cs index b7fd9b1cc..e0aa13851 100644 --- a/src/Samples/SimplificationIterableConsumer/IterableConsumerExample.cs +++ b/src/Samples/SimplificationIterableConsumer/IterableConsumerExample.cs @@ -31,7 +31,7 @@ internal static class IterableConsumerExample public static string SERVER = "nats://localhost:4222"; - public static void Main(String[] args) + public static void Main(string[] args) { Options opts = ConnectionFactory.GetDefaultOptions(SERVER); diff --git a/src/Samples/SimplificationMessageConsumer/MessageConsumerExample.cs b/src/Samples/SimplificationMessageConsumer/MessageConsumerExample.cs index 52f8eeaef..a01501c00 100644 --- a/src/Samples/SimplificationMessageConsumer/MessageConsumerExample.cs +++ b/src/Samples/SimplificationMessageConsumer/MessageConsumerExample.cs @@ -30,7 +30,7 @@ internal static class MessageConsumerExample private static readonly string SERVER = "nats://localhost:4222"; - public static void Main(String[] args) + public static void Main(string[] args) { Options opts = ConnectionFactory.GetDefaultOptions(SERVER); diff --git a/src/Samples/SimplificationNext/NextExample.cs b/src/Samples/SimplificationNext/NextExample.cs index ff2e4bdc2..6006ab0da 100644 --- a/src/Samples/SimplificationNext/NextExample.cs +++ b/src/Samples/SimplificationNext/NextExample.cs @@ -28,7 +28,7 @@ internal static class NextExample public static string SERVER = "nats://localhost:4222"; - public static void Main(String[] args) + public static void Main(string[] args) { Options opts = ConnectionFactory.GetDefaultOptions(SERVER); diff --git a/src/Tests/IntegrationTests/TestBasic.cs b/src/Tests/IntegrationTests/TestBasic.cs index 7d87727b4..d17d11776 100644 --- a/src/Tests/IntegrationTests/TestBasic.cs +++ b/src/Tests/IntegrationTests/TestBasic.cs @@ -1511,13 +1511,13 @@ public void TestLargeSubjectAndReply() { using (IConnection c = Context.OpenConnection()) { - String subject = ""; + string subject = ""; for (int i = 0; i < 1024; i++) { subject += "A"; } - String reply = ""; + string reply = ""; for (int i = 0; i < 1024; i++) { reply += "A"; diff --git a/src/Tests/IntegrationTests/TestEventHandler.cs b/src/Tests/IntegrationTests/TestEventHandler.cs index 98c33c156..60314b5bb 100644 --- a/src/Tests/IntegrationTests/TestEventHandler.cs +++ b/src/Tests/IntegrationTests/TestEventHandler.cs @@ -27,7 +27,7 @@ public EventHandler PullStatusErrorEventHandler options.PullStatusErrorEventHandler = PullStatusErrorEventHandler; }; - public bool PullStatusWarningOrWait(String contains, long timeout) + public bool PullStatusWarningOrWait(string contains, long timeout) { Stopwatch sw = Stopwatch.StartNew(); int i = 0; @@ -43,7 +43,7 @@ public bool PullStatusWarningOrWait(String contains, long timeout) return false; } - public bool PullStatusErrorOrWait(String contains, long timeout) + public bool PullStatusErrorOrWait(string contains, long timeout) { Stopwatch sw = Stopwatch.StartNew(); int i = 0; diff --git a/src/Tests/IntegrationTests/TestJetStream.cs b/src/Tests/IntegrationTests/TestJetStream.cs index 346cc7296..3299796c7 100644 --- a/src/Tests/IntegrationTests/TestJetStream.cs +++ b/src/Tests/IntegrationTests/TestJetStream.cs @@ -107,7 +107,7 @@ public void TestJetStreamSubscribe() { Msg m = s.NextMessage(DefaultTimeout); Assert.NotNull(m); Assert.Equal(DATA, Encoding.UTF8.GetString(m.Data)); - IList names = jsm.GetConsumerNames(STREAM); + IList names = jsm.GetConsumerNames(STREAM); Assert.Equal(1, names.Count); // default subscribe options // ephemeral subscription. @@ -377,10 +377,10 @@ public void TestBindExceptions() () => PushSubscribeOptions.Builder().WithDurable(DURABLE).WithBind(true).Build()); Assert.Throws( - () => PushSubscribeOptions.Builder().WithStream(String.Empty).WithBind(true).Build()); + () => PushSubscribeOptions.Builder().WithStream(string.Empty).WithBind(true).Build()); Assert.Throws( - () => PushSubscribeOptions.Builder().WithStream(STREAM).WithDurable(String.Empty).WithBind(true).Build()); + () => PushSubscribeOptions.Builder().WithStream(STREAM).WithDurable(string.Empty).WithBind(true).Build()); }); } @@ -535,7 +535,7 @@ private void SubscribeEx(IJetStream js, IJetStreamManagement jsm, string fs, str Assert.Contains(JsSubSubjectDoesNotMatchFilter.Id, e.Message); } - private void SetupConsumer(IJetStreamManagement jsm, int i, String fs) + private void SetupConsumer(IJetStreamManagement jsm, int i, string fs) { jsm.AddOrUpdateConsumer(STREAM, ConsumerConfiguration.Builder().WithDeliverSubject(Deliver(i)).WithDurable(Durable(i)).WithFilterSubject(fs).Build()); @@ -802,21 +802,21 @@ private void ChangeOkPull(IJetStream js, ConsumerConfiguration.ConsumerConfigura js.PullSubscribe(SUBJECT, PullSubscribeOptions.Builder().WithConfiguration(builder.Build()).Build()).Unsubscribe(); } - private void ChangeExPush(IJetStream js, ConsumerConfiguration.ConsumerConfigurationBuilder builder, String changedField) { + private void ChangeExPush(IJetStream js, ConsumerConfiguration.ConsumerConfigurationBuilder builder, string changedField) { NATSJetStreamClientException e = Assert.Throws( () => js.PushSubscribeSync(SUBJECT, PushSubscribeOptions.Builder().WithConfiguration(builder.Build()).Build())); _ChangeEx(e, changedField); } - private void ChangeExPull(IJetStream js, ConsumerConfiguration.ConsumerConfigurationBuilder builder, String changedField) { + private void ChangeExPull(IJetStream js, ConsumerConfiguration.ConsumerConfigurationBuilder builder, string changedField) { NATSJetStreamClientException e = Assert.Throws( () => js.PullSubscribe(SUBJECT, PullSubscribeOptions.Builder().WithConfiguration(builder.Build()).Build())); _ChangeEx(e, changedField); } - private void _ChangeEx(NATSJetStreamClientException e, String changedField) + private void _ChangeEx(NATSJetStreamClientException e, string changedField) { - String msg = e.Message; + string msg = e.Message; Assert.Contains(JsSubExistingConsumerCannotBeModified.Id, msg); Assert.Contains(changedField, msg); } diff --git a/src/Tests/IntegrationTests/TestJetStreamManagement.cs b/src/Tests/IntegrationTests/TestJetStreamManagement.cs index 308c902c9..131717c8a 100644 --- a/src/Tests/IntegrationTests/TestJetStreamManagement.cs +++ b/src/Tests/IntegrationTests/TestJetStreamManagement.cs @@ -250,7 +250,7 @@ public void TestGetStreamInfo() IJetStreamManagement jsm = c.CreateJetStreamManagementContext(); Assert.Throws(() => jsm.GetStreamInfo(STREAM)); - String[] subjects = new String[6]; + string[] subjects = new string[6]; for (int x = 0; x < 5; x++) { subjects[x] = Subject(x); } @@ -842,7 +842,7 @@ public void TestGetConsumers() private void AddConsumers(IJetStreamManagement jsm, string stream, int count, string durableVary, string filterSubject) { for (int x = 0; x < count; x++) { - String dur = Durable(durableVary, x + 1); + string dur = Durable(durableVary, x + 1); ConsumerConfiguration cc = ConsumerConfiguration.Builder() .WithDurable(dur) .WithFilterSubject(filterSubject) @@ -1007,7 +1007,7 @@ public void TestMessageGetRequest() ValidateMgr(1, null, "first", MessageGetRequest.NextForSubject(1, "first")); } - private void ValidateMgr(ulong seq, String lastBySubject, String nextBySubject, MessageGetRequest mgr) { + private void ValidateMgr(ulong seq, string lastBySubject, string nextBySubject, MessageGetRequest mgr) { Assert.Equal(seq, mgr.Sequence); Assert.Equal(lastBySubject, mgr.LastBySubject); Assert.Equal(nextBySubject, mgr.NextBySubject); diff --git a/src/Tests/IntegrationTests/TestJetStreamPull.cs b/src/Tests/IntegrationTests/TestJetStreamPull.cs index cd7a17e27..e8a487973 100644 --- a/src/Tests/IntegrationTests/TestJetStreamPull.cs +++ b/src/Tests/IntegrationTests/TestJetStreamPull.cs @@ -615,7 +615,7 @@ private void TestConflictStatus(string statusText, int type, string targetVersio }); } - private void CheckHandler(String statusText, int type, TestEventHandler handler) { + private void CheckHandler(string statusText, int type, TestEventHandler handler) { if (type == TypeError) { Assert.True(handler.PullStatusErrorOrWait(statusText, 10_000)); } diff --git a/src/Tests/IntegrationTests/TestObjectStore.cs b/src/Tests/IntegrationTests/TestObjectStore.cs index 26aab94d1..2c9e0c81c 100644 --- a/src/Tests/IntegrationTests/TestObjectStore.cs +++ b/src/Tests/IntegrationTests/TestObjectStore.cs @@ -152,7 +152,7 @@ public void TestWorkFlow() os.UpdateMeta(oi.ObjectName, ObjectMeta.ForObjectName(oi3.ObjectName)); // alternate puts - String name = "put-name-input-coverage"; + string name = "put-name-input-coverage"; expectedChunks = len / DefaultChunkSize; if (expectedChunks * DefaultChunkSize < len) { expectedChunks++; @@ -511,7 +511,7 @@ private void _testWatch(IConnection nc, TestObjectStoreWatcher watcher, object[] { IObjectStoreManagement osm = nc.CreateObjectStoreManagementContext(); - String bucket = watcher.Name + "Bucket"; + string bucket = watcher.Name + "Bucket"; osm.Create(ObjectStoreConfiguration.Builder(bucket).WithStorageType(StorageType.Memory).Build()); IObjectStore os = nc.CreateObjectStoreContext(bucket); diff --git a/src/Tests/IntegrationTestsInternal/TestService.cs b/src/Tests/IntegrationTestsInternal/TestService.cs index 032d55476..10506c2ba 100644 --- a/src/Tests/IntegrationTestsInternal/TestService.cs +++ b/src/Tests/IntegrationTestsInternal/TestService.cs @@ -116,7 +116,7 @@ public void TestServiceWorkflow() .AddServiceEndpoint(seSortA1) .AddServiceEndpoint(seSortD1) .Build(); - String serviceId1 = service1.Id; + string serviceId1 = service1.Id; Task serviceStoppedTask1 = service1.StartService(); Service service2 = new ServiceBuilder() @@ -127,7 +127,7 @@ public void TestServiceWorkflow() .AddServiceEndpoint(seSortA2) .AddServiceEndpoint(seSortD2) .Build(); - String serviceId2 = service2.Id; + string serviceId2 = service2.Id; Task serviceStoppedTask2 = service2.StartService(); Assert.NotEqual(serviceId1, serviceId2); @@ -149,13 +149,13 @@ public void TestServiceWorkflow() InfoResponse infoResponse2 = service2.InfoResponse; StatsResponse statsResponse1 = service1.GetStatsResponse(); StatsResponse statsResponse2 = service2.GetStatsResponse(); - EndpointResponse[] endpointResponseArray1 = new EndpointResponse[] + EndpointStats[] endpointStatsArray1 = new EndpointStats[] { service1.GetEndpointStats(EchoEndpointName), service1.GetEndpointStats(SortEndpointAscendingName), service1.GetEndpointStats(SortEndpointDescendingName) }; - EndpointResponse[] endpointResponseArray2 = new EndpointResponse[] + EndpointStats[] endpointStatsArray2 = new EndpointStats[] { service2.GetEndpointStats(EchoEndpointName), service2.GetEndpointStats(SortEndpointAscendingName), @@ -176,8 +176,8 @@ public void TestServiceWorkflow() for (int x = 0; x < 3; x++) { Assert.Equal(requestCount, - endpointResponseArray1[x].NumRequests - + endpointResponseArray2[x].NumRequests); + endpointStatsArray1[x].NumRequests + + endpointStatsArray2[x].NumRequests); Assert.Equal(requestCount, statsResponse1.EndpointStatsList[x].NumRequests + statsResponse2.EndpointStatsList[x].NumRequests); @@ -234,7 +234,7 @@ void VerifyStatsDiscovery(StatsResponse r, StatsResponse exp) { VerifyServiceResponseFields(r, exp); Assert.Equal(exp.Started, r.Started); for (int x = 0; x < 3; x++) { - EndpointResponse es = exp.EndpointStatsList[x]; + EndpointStats es = exp.EndpointStatsList[x]; if (!es.Name.Equals(EchoEndpointName)) { // echo endpoint has data that will vary Assert.Equal(es, r.EndpointStatsList[x]); @@ -288,7 +288,7 @@ private void VerifyServiceExecution(IConnection nc, string endpointName, string string request = DateTime.UtcNow.ToLongDateString(); // just some random text string subject = group == null ? serviceSubject : group.Subject + "." + serviceSubject; Msg m = nc.Request(subject, Encoding.UTF8.GetBytes(request)); - String response = Encoding.UTF8.GetString(m.Data); + string response = Encoding.UTF8.GetString(m.Data); switch (endpointName) { case EchoEndpointName: Assert.Equal(Echo(request), response); @@ -353,7 +353,6 @@ public void TestServiceBuilderConstruction() Assert.Null(service.Description); service = Service.Builder().WithConnection(conn).WithName(name).WithVersion("1.0.0").AddServiceEndpoint(se) - .WithApiUrl("apiUrl") .WithDescription("desc") .WithDrainTimeoutMillis(1000) .Build(); @@ -419,7 +418,7 @@ public void TestHandlerException() Assert.Equal("System.Exception: handler-problem", m.Header[ServiceMsg.NatsServiceError]); Assert.Equal("500", m.Header[ServiceMsg.NatsServiceErrorCode]); StatsResponse sr = exService.GetStatsResponse(); - EndpointResponse es = sr.EndpointStatsList[0]; + EndpointStats es = sr.EndpointStatsList[0]; Assert.Equal(1, es.NumRequests); Assert.Equal(1, es.NumErrors); Assert.Equal("System.Exception: handler-problem", es.LastError); @@ -558,7 +557,7 @@ public void TestEndpointConstruction() { Assert.Throws(() => Endpoint.Builder().Build()); // many names are bad - Assert.Throws(() => new Endpoint((String) null)); + Assert.Throws(() => new Endpoint((string) null)); Assert.Throws(() => new Endpoint(string.Empty)); Assert.Throws(() => new Endpoint(HasSpace)); Assert.Throws(() => new Endpoint(HasPrintable)); @@ -581,11 +580,11 @@ public void TestEndpointConstruction() { } [Fact] - public void TestEndpointResponseConstruction() + public void TestEndpointStatsConstruction() { DateTime zdt = DateTime.UtcNow; - EndpointResponse er = new EndpointResponse("name", "subject", 0, 0, 0, null, null, zdt); + EndpointStats er = new EndpointStats("name", "subject", 0, 0, 0, null, null, zdt); Assert.Equal("name", er.Name); Assert.Equal("subject", er.Subject); Assert.Null(er.LastError); @@ -597,7 +596,7 @@ public void TestEndpointResponseConstruction() Assert.Equal(zdt, er.Started); JSONNode data = new JSONString("data"); - er = new EndpointResponse("name", "subject", 2, 4, 10, "lastError", data, zdt); + er = new EndpointStats("name", "subject", 2, 4, 10, "lastError", data, zdt); Assert.Equal("name", er.Name); Assert.Equal("subject", er.Subject); Assert.Equal("lastError", er.LastError); @@ -618,7 +617,7 @@ public void TestEndpointResponseConstruction() Assert.Contains("\"num_errors\":4", j); Assert.Contains("\"processing_time\":10", j); Assert.Contains("\"average_processing_time\":5", j); - Assert.Equal(JsonUtils.ToKey(typeof(EndpointResponse)) + j, er.ToString()); + Assert.Equal(JsonUtils.ToKey(typeof(EndpointStats)) + j, er.ToString()); } [Fact] @@ -705,7 +704,7 @@ public void TestServiceEndpointConstruction() se = ServiceEndpoint.Builder() .WithEndpoint(e1) - .WithEndpoint(e2) + .WithEndpoint(e2) // last one wins .WithHandler(smh) .Build(); Assert.Equal(e2, se.Endpoint); @@ -727,7 +726,23 @@ public void TestServiceEndpointConstruction() .Build(); Assert.Equal(e1.Name, se.Name); Assert.Equal(e2.Subject, se.Subject); + + IDictionary metadata = new Dictionary(); + se = ServiceEndpoint.Builder() + .WithEndpoint(e1) + .WithEndpointMetadata(metadata) + .WithHandler(smh) + .Build(); + Assert.Null(se.Metadata); + metadata["k"] = "v"; + se = ServiceEndpoint.Builder() + .WithEndpoint(e1) + .WithEndpointMetadata(metadata) + .WithHandler(smh) + .Build(); + Assert.True(Validator.DictionariesEqual(metadata, se.Metadata)); + ArgumentException iae = Assert.Throws( () => ServiceEndpoint.Builder().Build()); Assert.Contains("Endpoint", iae.Message); @@ -794,10 +809,10 @@ public void TestServiceResponsesConstruction() Thread.Sleep(100); endStarteds[1] = DateTime.UtcNow; - IList statsList = new List(); + IList statsList = new List(); JSONNode[] data = new JSONNode[]{SupplyData(), SupplyData()}; - statsList.Add(new EndpointResponse("endName0", "endSubject0", 1000, 0, 10000, "lastError0", data[0], endStarteds[0])); - statsList.Add(new EndpointResponse("endName1", "endSubject1", 2000, 10, 10000, "lastError1", data[1], endStarteds[1])); + statsList.Add(new EndpointStats("endName0", "endSubject0", 1000, 0, 10000, "lastError0", data[0], endStarteds[0])); + statsList.Add(new EndpointStats("endName1", "endSubject1", 2000, 10, 10000, "lastError1", data[1], endStarteds[1])); StatsResponse stat1 = new StatsResponse(pr1, serviceStarted, statsList); StatsResponse stat2 = new StatsResponse(stat1.ToJsonString()); @@ -811,7 +826,7 @@ private static void ValidateApiInOutStatsResponse(StatsResponse stat, DateTime s Assert.Equal(serviceStarted, stat.Started); Assert.Equal(2, stat.EndpointStatsList.Count); for (int x = 0; x < 2; x++) { - EndpointResponse e = stat.EndpointStatsList[x]; + EndpointStats e = stat.EndpointStatsList[x]; Assert.Equal("endName" + x, e.Name); Assert.Equal("endSubject" + x, e.Subject); long nr = x * 1000 + 1000; diff --git a/src/Tests/UnitTests/Internals/TestValidator.cs b/src/Tests/UnitTests/Internals/TestValidator.cs index 5f478fcc7..8dc2d7c40 100644 --- a/src/Tests/UnitTests/Internals/TestValidator.cs +++ b/src/Tests/UnitTests/Internals/TestValidator.cs @@ -33,48 +33,48 @@ public TestValidator() public void TestValidateMessageSubjectRequired() { AllowedRequired(ValidateSubject, Plain, HasPrintable, HasDot, HasStar, HasGt, HasDollar); - NotAllowedRequired(ValidateSubject, null, String.Empty, HasSpace, HasLow, Has127); + NotAllowedRequired(ValidateSubject, null, string.Empty, HasSpace, HasLow, Has127); NotAllowedRequired(ValidateSubject, _utfOnlyStrings); - AllowedNotRequiredEmptyAsNull(ValidateSubject, null, String.Empty); + AllowedNotRequiredEmptyAsNull(ValidateSubject, null, string.Empty); - NotAllowedRequired(ValidateSubject, null, String.Empty, HasSpace, HasLow, Has127); - AllowedNotRequiredEmptyAsNull(ValidateSubject, null, String.Empty); + NotAllowedRequired(ValidateSubject, null, string.Empty, HasSpace, HasLow, Has127); + AllowedNotRequiredEmptyAsNull(ValidateSubject, null, string.Empty); } [Fact] public void TestValidateReplyTo() { AllowedRequired(ValidateReplyTo, Plain, HasPrintable, HasDot, HasDollar); - NotAllowedRequired(ValidateReplyTo, null, String.Empty, HasSpace, HasStar, HasGt, HasLow, Has127); + NotAllowedRequired(ValidateReplyTo, null, string.Empty, HasSpace, HasStar, HasGt, HasLow, Has127); NotAllowedRequired(ValidateReplyTo, _utfOnlyStrings); - AllowedNotRequiredEmptyAsNull(ValidateReplyTo, null, String.Empty); + AllowedNotRequiredEmptyAsNull(ValidateReplyTo, null, string.Empty); } [Fact] public void TestValidateQueueNameRequired() { AllowedRequired(ValidateQueueName, Plain, HasPrintable, HasDollar); - NotAllowedRequired(ValidateQueueName, null, String.Empty, HasSpace, HasDot, HasStar, HasGt, HasLow, Has127); + NotAllowedRequired(ValidateQueueName, null, string.Empty, HasSpace, HasDot, HasStar, HasGt, HasLow, Has127); NotAllowedRequired(ValidateQueueName, _utfOnlyStrings); - AllowedNotRequiredEmptyAsNull(ValidateQueueName, null, String.Empty); + AllowedNotRequiredEmptyAsNull(ValidateQueueName, null, string.Empty); } [Fact] public void TestValidateStreamName() { AllowedRequired(ValidateStreamName, Plain, HasPrintable, HasDollar); - NotAllowedRequired(ValidateStreamName, null, String.Empty, HasSpace, HasDot, HasStar, HasGt, HasLow, Has127); + NotAllowedRequired(ValidateStreamName, null, string.Empty, HasSpace, HasDot, HasStar, HasGt, HasLow, Has127); NotAllowedRequired(ValidateStreamName, _utfOnlyStrings); - AllowedNotRequiredEmptyAsNull(ValidateStreamName, null, String.Empty); + AllowedNotRequiredEmptyAsNull(ValidateStreamName, null, string.Empty); } [Fact] public void TestValidateDurable() { AllowedRequired(ValidateDurable, Plain, HasPrintable, HasDollar); - NotAllowedRequired(ValidateDurable, null, String.Empty, HasSpace, HasDot, HasStar, HasGt, HasLow, Has127); + NotAllowedRequired(ValidateDurable, null, string.Empty, HasSpace, HasDot, HasStar, HasGt, HasLow, Has127); NotAllowedRequired(ValidateDurable, _utfOnlyStrings); - AllowedNotRequiredEmptyAsNull(ValidateDurable, null, String.Empty); + AllowedNotRequiredEmptyAsNull(ValidateDurable, null, string.Empty); } [Fact] @@ -251,21 +251,21 @@ public void TestZeroOrLtMinus1() Assert.False(ZeroOrLtMinus1(-1)); } - private void AllowedRequired(Func test, params String[] strings) + private void AllowedRequired(Func test, params string[] strings) { foreach (string s in strings) { Assert.Equal(s, test.Invoke(s, true)); } } - private void AllowedNotRequiredEmptyAsNull(Func test, params String[] strings) + private void AllowedNotRequiredEmptyAsNull(Func test, params string[] strings) { foreach (string s in strings) { Assert.Null(test.Invoke(s, false)); } } - private void NotAllowedRequired(Func test, params String[] strings) + private void NotAllowedRequired(Func test, params string[] strings) { foreach (string s in strings) { @@ -283,7 +283,7 @@ public void TestNatsJetStreamClientError() [Fact] public void TestSemVer() { - String label = "Version"; + string label = "Version"; ValidateSemVer("0.0.4", label, true); ValidateSemVer("1.2.3", label, true); ValidateSemVer("10.20.30", label, true); diff --git a/src/Tests/UnitTests/JetStream/TestApiResponse.cs b/src/Tests/UnitTests/JetStream/TestApiResponse.cs index d2b3f98ac..2367dc5ae 100644 --- a/src/Tests/UnitTests/JetStream/TestApiResponse.cs +++ b/src/Tests/UnitTests/JetStream/TestApiResponse.cs @@ -11,7 +11,6 @@ // See the License for the specific language governing permissions and // limitations under the License. -using System; using NATS.Client.JetStream; using Xunit; @@ -34,7 +33,7 @@ public void DoesNotHaveAnError() { [Fact] public void MiscErrorResponsesAreUnderstood() { string text = ReadDataFile("ErrorResponses.json.txt"); - String[] jsons = text.Split('~'); + string[] jsons = text.Split('~'); TestingApiResponse jsApiResp = new TestingApiResponse(jsons[0]); Assert.True(jsApiResp.HasError); diff --git a/src/Tests/UnitTests/JetStream/TestObjectStoreApi.cs b/src/Tests/UnitTests/JetStream/TestObjectStoreApi.cs index 4b833fd35..e19313bf3 100644 --- a/src/Tests/UnitTests/JetStream/TestObjectStoreApi.cs +++ b/src/Tests/UnitTests/JetStream/TestObjectStoreApi.cs @@ -85,7 +85,7 @@ void ValidateObjectInfo(ObjectInfo oi, DateTime modified) Assert.True(oi.IsDeleted); Assert.Equal(modified, oi.Modified); Assert.Equal(2, oi.Headers.Count); - IList list = oi.Headers.GetValues(Key(1)); + IList list = oi.Headers.GetValues(Key(1)); Assert.Equal(1, list.Count); Assert.Equal(Data(1), oi.Headers[Key(1)]); list = oi.Headers.GetValues(Key(2)); diff --git a/src/Tests/UnitTests/JetStream/TestPublishAck.cs b/src/Tests/UnitTests/JetStream/TestPublishAck.cs index 439365585..25b0f6298 100644 --- a/src/Tests/UnitTests/JetStream/TestPublishAck.cs +++ b/src/Tests/UnitTests/JetStream/TestPublishAck.cs @@ -11,7 +11,6 @@ // See the License for the specific language governing permissions and // limitations under the License. -using System; using NATS.Client; using NATS.Client.JetStream; using Xunit; @@ -22,7 +21,7 @@ public class TestPublishAck { [Fact] public void IsValidAck() { - String json = "{\"stream\":\"test-stream\",\"seq\":42,\"domain\":\"test-domain\", \"duplicate\" : true }"; + string json = "{\"stream\":\"test-stream\",\"seq\":42,\"domain\":\"test-domain\", \"duplicate\" : true }"; PublishAck ack = new PublishAck(json); Assert.Equal("test-stream", ack.Stream); @@ -33,7 +32,7 @@ public void IsValidAck() { [Fact] public void ThrowsOnERR() { - String json ="{" + + string json ="{" + " \"type\": \"io.nats.jetstream.api.v1.pub_ack_response\"," + " \"error\": {" + " \"code\": 500," + @@ -49,7 +48,7 @@ public void ThrowsOnERR() { [Fact] public void InvalidResponse() { - String json1 = "+OK {" + + string json1 = "+OK {" + "\"missing_stream\":\"test\"" + "," + "\"missing_seq\":\"0\"" + "}"; @@ -57,7 +56,7 @@ public void InvalidResponse() { NATSException ioe = Assert.Throws(() => new PublishAck(json1)); Assert.Equal("Invalid JetStream ack.", ioe.Message); - String json2 = "{\"stream\":\"test\", \"duplicate\" : true }"; + string json2 = "{\"stream\":\"test\", \"duplicate\" : true }"; Assert.Throws(() => new PublishAck(json2)); } } diff --git a/src/Tests/UnitTests/JetStream/TestServerInfoObject.cs b/src/Tests/UnitTests/JetStream/TestServerInfoObject.cs index 7b0cfb0f1..ae17452cc 100644 --- a/src/Tests/UnitTests/JetStream/TestServerInfoObject.cs +++ b/src/Tests/UnitTests/JetStream/TestServerInfoObject.cs @@ -11,7 +11,6 @@ // See the License for the specific language governing permissions and // limitations under the License. -using System; using NATS.Client.Internals; using NATS.Client.JetStream; using Xunit; @@ -67,7 +66,7 @@ public void ServerVersionComparisonsWork() ServerInfo si = infos[i]; for (int j = 0; j < infos.Length; j++) { - String v2 = new ServerVersion(infos[j].Version).ToString(); + string v2 = new ServerVersion(infos[j].Version).ToString(); if (i == j) { Assert.True(si.IsSameVersion(v2)); @@ -113,7 +112,7 @@ public void ServerVersionComparisonsWork() [Fact] public void EmptyUrlParsedProperly() { - String json = "INFO {" + + string json = "INFO {" + "\"server_id\":\"myserver\"" + "," + "\"connect_urls\":[\"one\", \"\"]" + "}"; @@ -128,7 +127,7 @@ public void EmptyUrlParsedProperly() [Fact] public void IPV6InBracketsParsedProperly() { - String json = "INFO {" + + string json = "INFO {" + "\"server_id\":\"myserver\"" + "," + "\"connect_urls\":[\"one:4222\", \"[a:b:c]:4222\", \"[d:e:f]:4223\"]" + "," + "\"max_payload\":100000000000" + @@ -143,7 +142,7 @@ public void IPV6InBracketsParsedProperly() [Fact] public void EncodingInString() { - String json = "INFO {" + + string json = "INFO {" + "\"server_id\":\"\\\\\\b\\f\\n\\r\\t\"" + "," + "\"go\":\"my\\u0021go\"" + "," + "\"host\":\"my\\\\host\"" + "," + diff --git a/src/Tests/UnitTests/TestBase.cs b/src/Tests/UnitTests/TestBase.cs index 8f1e8e6e4..ce08ce9e2 100644 --- a/src/Tests/UnitTests/TestBase.cs +++ b/src/Tests/UnitTests/TestBase.cs @@ -95,7 +95,7 @@ public static string TempConfFile() return Path.GetTempPath() + "nats_net_test" + Guid.NewGuid() + ".conf"; } - public string[] SplitLines(String text) + public string[] SplitLines(string text) { return text.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None); } @@ -125,7 +125,7 @@ public static string Stream(object seq) return $"{STREAM}-{seq}"; } - public static string Field(String field, object seq) + public static string Field(string field, object seq) { return $"{field}-{seq}"; } diff --git a/src/Tests/UnitTests/TestNUID.cs b/src/Tests/UnitTests/TestNUID.cs index 87994786b..d61066825 100644 --- a/src/Tests/UnitTests/TestNUID.cs +++ b/src/Tests/UnitTests/TestNUID.cs @@ -103,7 +103,7 @@ public void TestNuidBasicUniqueess() for (int i = 0; i < count; i++) { - String n = NUID.NextGlobal; + string n = NUID.NextGlobal; Assert.False(m.ContainsKey(n), string.Format("Duplicate NUID found: {0}", n)); m.Add(n, true);