public async Task Client_Should_be_able_to_publish_and_consume_messages_When_publishing_batch() { var subject = Context.GenerateSubject(); var messages = new[] { "My test string\r\nwith two lines and\ttabs!", "Foo bar!", "My async test string\r\nwith two lines and\ttabs!", "Async Foo bar!" }; _sync = Sync.Max(4); _client1 = await Context.ConnectClientAsync(); _client1.MsgOpStream.Subscribe(msg => _sync.Release(msg)); _client1.Sub(subject); await Context.DelayAsync(); _client1.PubMany(async p => { p.Pub(subject, messages[0]); p.Pub(subject, Encoding.UTF8.GetBytes(messages[1])); await p.PubAsync(subject, messages[2]); await p.PubAsync(subject, Encoding.UTF8.GetBytes(messages[3])); }); _sync.WaitForAll(); _sync.InterceptedCount.Should().Be(messages.Length); _sync.Intercepted.Select(m => m.GetPayloadAsString()).ToArray().Should().Contain(messages); }
public static async Task RunAsync(ConnectionInfo cnInfo) { using (var client = new NatsClient("Publisher", cnInfo)) { client.Connect(); while (true) { Console.WriteLine("Say what? (blank=quit)"); var message = Console.ReadLine(); if (string.IsNullOrWhiteSpace(message)) { break; } Console.WriteLine("To what \"Child\" Subject? (blank=quit)"); var subject = Console.ReadLine(); if (string.IsNullOrWhiteSpace(subject)) { break; } await client.PubAsync($"demo.{subject}", message); } } }
public static async Task RunAsync(ConnectionInfo cnInfo) { using (var client = new NatsClient("Sample8", cnInfo)) { //Subscribe directly to MsgOpStream client.MsgOpStream .Where(msgOp => msgOp.Subject == "demo.a") .Select(msgOp => msgOp.GetPayloadAsString()) .Subscribe(msg => Console.WriteLine($"A: {msg}")); client.MsgOpStream .Where(msgOp => msgOp.Subject == "demo.b") .Select(msgOp => msgOp.GetPayloadAsString()) .Subscribe(msg => Console.WriteLine($"B: {msg}")); //OpStream gets all incoming Ops. Like MsgOp, Ping, Pong... client.OpStream .OfType <MsgOp>() .Select(msgOp => msgOp.GetAsString().Length) .Subscribe(len => Console.WriteLine($"Len: {len}")); client.Connect(); //Tell NATS server we are interested in all subjects //under "demo". So we only have one NATS Server subscription await client.SubAsync("demo.>"); Console.WriteLine("Hit key to quit."); Console.ReadKey(); } }
public static Task RunAsync(ConnectionInfo cnInfo) { using (var client = new NatsClient("Publisher", cnInfo)) { client.Connect(); while (true) { Console.WriteLine("Say what? (blank=quit)"); var message = Console.ReadLine(); if (string.IsNullOrWhiteSpace(message)) { break; } int n; Console.WriteLine("How many? (blank=quit)"); if (!int.TryParse(Console.ReadLine(), out n)) { break; } client.PubMany(p => { for (var c = 0; c < n; c++) { p.Pub("demo", message); } }); } } return(Task.CompletedTask); }
public async Task Client_Should_be_able_to_handle_large_message_When_using_explicit_flush_although_auto_flush(int messageCount) { var message = new string('b', 16384); var exceptions = new List <Exception>(); var subject = Context.GenerateSubject(); var cnInfo = Context.GetConnectionInfo(); cnInfo.PubFlushMode = PubFlushMode.Auto; _sync = Sync.Max(messageCount); _client1 = await Context.ConnectClientAsync(cnInfo); _client1.Events.OfType <ClientWorkerFailed>().Subscribe(ev => exceptions.Add(ev.Exception)); _client1.OpStream.OfType <MsgOp>().SubscribeSafe(msg => _sync.Release(msg), ex => exceptions.Add(ex)); await _client1.SubAsync(subject); await Context.DelayAsync(); for (var i = 0; i < messageCount; i++) { await _client1.PubAsync(subject, message); await _client1.FlushAsync(); } _sync.WaitForAll(); exceptions.Should().BeEmpty(); _sync.InterceptedCount.Should().Be(messageCount); _sync.Intercepted .Select(m => m.GetPayloadAsString()) .Should().OnlyContain(m => m == message); }
/// <summary> /// Subscribes to the specified url. /// </summary> /// <param name="url">The connection url.</param> public void Subscribe(string url) { var uri = new Uri(url); _cnInfo = new ConnectionInfo(uri.Host, uri.Port == -1?null:(int?)uri.Port); _client = new NatsClient(_cnInfo); }
public async Task Client_Should_throw_if_pub_after_disconnected() { var subject = Context.GenerateSubject(); var body = new byte[0]; _client1 = await Context.ConnectClientAsync(); // Succeeds _client1.Pub(subject, "body"); _client1.Pub(subject, "body", "repy.to.subject"); _client1.Pub(subject, body.AsMemory()); _client1.Pub(subject, body.AsMemory(), "repy.to.subject"); // Disconnect from NATS per user request _client1.Disconnect(); Assert.False(_client1.IsConnected); // Fails after being disconnected Should.ThrowNatsException(() => _client1.Pub(subject, "body")); Should.ThrowNatsException(() => _client1.Pub(subject, "body", "reply.to.subject")); Should.ThrowNatsException(() => _client1.Pub(subject, body.AsMemory())); Should.ThrowNatsException(() => _client1.Pub(subject, body.AsMemory(), "reply.to.subject")); await Should.ThrowNatsExceptionAsync(() => _client1.PubAsync(subject, "body")); await Should.ThrowNatsExceptionAsync(() => _client1.PubAsync(subject, "body", "reply.to.subject")); await Should.ThrowNatsExceptionAsync(() => _client1.PubAsync(subject, body.AsMemory())); await Should.ThrowNatsExceptionAsync(() => _client1.PubAsync(subject, body.AsMemory(), "reply.to.subject")); }
private static async Task <NatsClient> Connect(int port = 4222) { var hostname = _isCi ? $"nats-{port - 4222}" : "localhost"; var cancellationToken = new CancellationTokenSource(_timeout).Token; return(await NatsClient.Connect(hostname, port, _natsOptions, cancellationToken)); }
public async Task Given_subscribed_async_using_handler_When_the_subscription_has_been_disposed_It_should_not_get_messages() { var subject = Context.GenerateSubject(); _sync = Sync.MaxOne(); _client = await Context.ConnectClientAsync(); var s = await _client.SubAsync(subject, stream => stream.Subscribe(msg => _sync.Release(msg))); await Context.DelayAsync(); await _client.PubAsync(subject, "Test1"); _sync.WaitForAny(); await _client.PubAsync(subject, "Test2"); _sync.WaitForAny(); s.Dispose(); await _client.PubAsync(subject, "Test3"); await Context.DelayAsync(); _sync.InterceptedCount.Should().Be(2); }
public async Task Client_Should_throw_if_request_after_disconnected() { var subject = Context.GenerateSubject(); var body = new byte[0]; _responder = await Context.ConnectClientAsync(); _requester = await Context.ConnectClientAsync(); _responder.Sub(subject, stream => stream.Subscribe(msg => _responder.Pub(msg.ReplyTo, msg.GetPayloadAsString()))); await Context.DelayAsync(); // Succeeds var response = await _requester.RequestAsync(subject, "body"); Assert.NotNull(response); response = await _requester.RequestAsync(subject, body.AsMemory()); Assert.NotNull(response); // Disconnect from NATS per user request _requester.Disconnect(); Assert.False(_requester.IsConnected); // Fails after being disconnected await Should.ThrowNatsExceptionAsync(() => _requester.RequestAsync(subject, "body")); await Should.ThrowNatsExceptionAsync(() => _requester.RequestAsync(subject, body.AsMemory())); }
public static async Task RunAsync(ConnectionInfo cnInfo) { using (var client = new NatsClient("Sample4", cnInfo)) { client.Connect(); //Observer lets you react on exceptions etc //Send "fail" to have it fail await client.SubWithObserverAsync( "demo", new DelegatingObserver <MsgOp>( msgOp => { var msg = msgOp.GetPayloadAsString(); if (msg == "fail") { throw new Exception("Oh no!"); } Console.WriteLine(msg); }, ex => Console.WriteLine($"Bad times! {ex}"))); //You can have an "generic" handler for exceptions as well client.MsgOpStream.OnException = (msgOp, ex) => Console.WriteLine($"Worse times! {ex}"); //If logging is all you need you can also hook into //LoggerManager.Resolve Console.WriteLine("Hit key to quit."); Console.ReadKey(); } }
public async Task Given_multiple_responders_exists_When_requesting_It_should_return_one_response() { var value = Guid.NewGuid().ToString("N"); var responderReplyingCount = 0; var responderReplyCount = 0; _requester.MsgOpStream.Subscribe(msgOp => Interlocked.Increment(ref responderReplyCount)); _responder.Sub("getValue", stream => stream.Subscribe(msg => { Interlocked.Increment(ref responderReplyingCount); _responder.Pub(msg.ReplyTo, msg.GetPayloadAsString()); })); MsgOp response; using (var responder2 = new NatsClient(ConnectionInfo)) { responder2.Connect(); responder2.Sub("getValue", stream => stream.Subscribe(msg => { Interlocked.Increment(ref responderReplyingCount); responder2.Pub(msg.ReplyTo, msg.GetPayloadAsString()); })); response = await _requester.RequestAsync("getValue", value); } response.GetPayloadAsString().Should().Be(value); responderReplyCount.Should().Be(1); responderReplyingCount.Should().Be(2); }
public async Task Client_Should_be_able_to_publish_When_no_subscribers_exists() { _client1 = await Context.ConnectClientAsync(); _client1.Pub("Test", "test message"); await _client1.PubAsync("Test", "Test message"); }
public async Task Given_subscribed_with_overlapping_wildcards_async_using_handler_It_should_get_only_subcription_messages() { const string subjectNs = "foo.tests."; _sync = Sync.MaxOne(); _client = await Context.ConnectClientAsync(); // First subscription await _client.SubAsync(subjectNs + ">"); // Second, overlapping subscription var subscription = await _client.SubAsync(subjectNs + "*", stream => stream.Subscribe(msg => _sync.Release(msg))); await Context.DelayAsync(); await _client.PubAsync(subjectNs + "type1", "Test1"); _sync.WaitForAny(); await _client.PubAsync(subjectNs + "type2", "Test2"); _sync.WaitForAny(); await _client.PubAsync(subjectNs + "type3", "Test3"); _sync.WaitForAny(); _sync.InterceptedCount.Should().Be(3); _sync.Intercepted.Select(i => i.SubscriptionId).Should().OnlyContain(i => i == subscription.SubscriptionInfo.Id); }
public async Task Given_subscribed_When_unsubscribing_async_It_should_not_get_any_further_messages() { var subject = Context.GenerateSubject(); _sync = Sync.MaxOne(); _client = await Context.ConnectClientAsync(); var s = _client.Sub(subject, stream => stream.Subscribe(NatsObserver.Delegating <MsgOp>(msg => _sync.Release(msg)))); await Context.DelayAsync(); await _client.PubAsync(subject, "Test1"); _sync.WaitForAny(); await _client.PubAsync(subject, "Test2"); _sync.WaitForAny(); await _client.UnsubAsync(s.SubscriptionInfo); await _client.PubAsync(subject, "Test3"); await Context.DelayAsync(); _sync.InterceptedCount.Should().Be(2); }
/// <summary> /// Serves the asynchronous. /// </summary> /// <param name="request">The request.</param> /// <returns></returns> public async Task <JsonRpcResponse> ServeAsync(JsonRpcRequest request) { if (_disposed) { throw new ObjectDisposedException(typeof(JsonRpcServer).Name); } using (var client = new NatsClient(_connectionInfo)) { try { client.Connect(); var response = await client.RequestAsync(request.Method, EncodeRequest(request), _timeout); var data = DecodeResponse(response.Payload); return(data); } catch (NatsRequestTimedOutException e) { throw new JsonRpcException(ErrorCode.InternalError, e.Message); } catch (Exception ex) { throw new JsonRpcException(ErrorCode.InternalError, ex.Message); } } }
/// <summary> /// Initializes a new instance of the <see cref="AlpacaBrokerage"/> class. /// </summary> /// <param name="orderProvider">The order provider.</param> /// <param name="securityProvider">The holdings provider.</param> /// <param name="accountKeyId">The Alpaca api key id</param> /// <param name="secretKey">The api secret key</param> /// <param name="tradingMode">The Alpaca trading mode. paper/live</param> public AlpacaBrokerage(IOrderProvider orderProvider, ISecurityProvider securityProvider, string accountKeyId, string secretKey, string tradingMode) : base("Alpaca Brokerage") { var baseUrl = "api.alpaca.markets"; if (tradingMode.Equals("paper")) { baseUrl = "paper-" + baseUrl; } baseUrl = "https://" + baseUrl; _orderProvider = orderProvider; _securityProvider = securityProvider; _marketHours = MarketHoursDatabase.FromDataFolder(); // api client for alpaca _restClient = new RestClient(accountKeyId, secretKey, baseUrl); // websocket client for alpaca _sockClient = new SockClient(accountKeyId, secretKey, baseUrl); _sockClient.OnTradeUpdate += OnTradeUpdate; _sockClient.OnError += OnSockClientError; // polygon client for alpaca _natsClient = new NatsClient(accountKeyId, baseUrl.Contains("staging")); _natsClient.QuoteReceived += OnQuoteReceived; _natsClient.TradeReceived += OnTradeReceived; _natsClient.OnError += OnNatsClientError; }
public ClientRequestTests() { _requester = new NatsClient(ConnectionInfo); _requester.Connect(); _responder = new NatsClient(ConnectionInfo); _responder.Connect(); }
public async Task Given_no_responder_exists_When_requesting_It_should_get_cancelled() { _requester = await Context.ConnectClientAsync(); Func <Task> a = async() => await _requester.RequestAsync("getValue", "foo value"); a.Should().Throw <TaskCanceledException>(); }
private async Task ConnectAllClients() { _client1 = await Context.ConnectClientAsync(); _client2 = await Context.ConnectClientAsync(); _client3 = await Context.ConnectClientAsync(); }
public async Task <Message> PublishMessageToTopic(Message msg) { NatsClient <Message> client = new NatsClient <Message>(); await Task.Run(() => client.Publish(TopicName, msg)); return(msg); }
/// <summary> /// Create Nats Client from connection string /// </summary> /// <param name="connstring">Connection String</param> /// <returns>Returns NatsClient</returns> public NatsClient CreateNatsClient(string connstring) { NatsClient client = new NatsClient(); client.Connect(connstring); return(client); }
public void Dispose() { _sync?.Dispose(); _sync = null; _client?.Disconnect(); _client?.Dispose(); _client = null; }
public async Task Given_not_connected_Should_be_able_to_subscribe_async() { _client = Context.CreateClient(); var sub = await _client.SubAsync(Context.GenerateSubject()); sub.Should().NotBeNull(); _client.IsConnected.Should().BeFalse(); }
public async Task GetSubscriptionTest() { const string subject = "some_subject"; const string paload = "some payload"; var encodedPayload = Encoding.UTF8.GetBytes(paload); string subscriptionId = null; var resetEvent = new ManualResetEvent(false); var messageSubject = new Subject <Message <IncomingMessage> >(); var mockNatsConnection = new Mock <INatsConnection>(); mockNatsConnection .Setup(x => x.Write(It.IsAny <byte[]>(), It.IsAny <CancellationToken>())) .Returns <byte[], CancellationToken>((data, _) => { var message = Encoding.UTF8.GetString(data); var match = Regex.Match(message, $"^SUB {subject} ([^ \r\n]+)\r\n$"); if (match.Success) { subscriptionId = match.Groups[1].Value; resetEvent.Set(); } return(Task.CompletedTask); }); mockNatsConnection.Setup(x => x.Messages).Returns(messageSubject); mockNatsConnection.Setup(x => x.OnConnect).Returns(Observable.Return(new ServerInfo())); mockNatsConnection.Setup(x => x.ConnectionState).Returns(NatsConnectionState.Connected); using (var client = new NatsClient(mockNatsConnection.Object)) { var subscription = client.GetSubscription(subject) .FirstAsync() .Timeout(_timeout) .ToTask(); resetEvent.WaitOne(_timeout); var incomingMessage = new IncomingMessage(subject, subscriptionId, string.Empty, encodedPayload.Length, encodedPayload); messageSubject.OnNext(Message.From("MSG", incomingMessage)); var message = await subscription; Assert.Equal(incomingMessage, message); } mockNatsConnection.Verify(x => x.Write( It.Is <byte[]>(data => Encoding.UTF8.GetString(data).StartsWith($"SUB {subject} ")), It.IsAny <CancellationToken>()), Times.Once); mockNatsConnection.Verify(x => x.Write( It.Is <byte[]>(data => Encoding.UTF8.GetString(data).Contains($"UNSUB {subscriptionId}\r\n")), It.IsAny <CancellationToken>())); }
public void Dispose() { _requester?.Disconnect(); _requester?.Dispose(); _requester = null; _responder?.Disconnect(); _responder?.Dispose(); _responder = null; }
protected override void OnAfterEachTest() { _requester?.Disconnect(); _requester?.Dispose(); _requester = null; _responder?.Disconnect(); _responder?.Dispose(); _responder = null; }
public ClientUnSubTests() { _client1 = new NatsClient(ConnectionInfo); _client1.Connect(); _client2 = new NatsClient(ConnectionInfo); _client2.Connect(); _client3 = new NatsClient(ConnectionInfo); _client3.Connect(); }
public async Task Client_Should_throw_if_request_when_never_connected() { var subject = Context.GenerateSubject(); var body = new byte[0]; _requester = Context.CreateClient(); await Should.ThrowNatsExceptionAsync(() => _requester.RequestAsync(subject, "body")); await Should.ThrowNatsExceptionAsync(() => _requester.RequestAsync(subject, body.AsMemory())); }
public async Task Given_not_connected_Should_be_able_to_connect_with_specific_name() { var connectionInfo = Context.GetConnectionInfo(); connectionInfo.Name = Guid.NewGuid().ToString("N"); _client = await Context.ConnectClientAsync(connectionInfo); await Context.DelayAsync(); _client.IsConnected.Should().BeTrue(); }