Ejemplo n.º 1
0
        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()));
        }
Ejemplo n.º 2
0
        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"));
        }
Ejemplo n.º 3
0
        public void Dispose()
        {
            _sync?.Dispose();
            _sync = null;

            _client?.Disconnect();
            _client?.Dispose();
            _client = null;
        }
Ejemplo n.º 4
0
        protected override void OnAfterEachTest()
        {
            _requester?.Disconnect();
            _requester?.Dispose();
            _requester = null;

            _responder?.Disconnect();
            _responder?.Dispose();
            _responder = null;
        }
Ejemplo n.º 5
0
        public void Dispose()
        {
            _requester?.Disconnect();
            _requester?.Dispose();
            _requester = null;

            _responder?.Disconnect();
            _responder?.Dispose();
            _responder = null;
        }
Ejemplo n.º 6
0
        protected override async Task DoWork(PairConfig pair, CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                try
                {
                    using (BinanceSocketClient client = new BinanceSocketClient())
                    {
                        ConnectionInfo cnInfo = new ConnectionInfo(_settings.Value.BusConnectionString);
                        using (NatsClient natsClient = new NatsClient(cnInfo))
                        {
                            if (!natsClient.IsConnected)
                            {
                                natsClient.Connect();
                            }

                            CallResult <UpdateSubscription> successKline = null;
                            successKline = client.SubscribeToTradeUpdates(pair.Symbol, async(data) =>
                            {
                                Trade trade = data.ToEntity();

                                if (!_settings.Value.DisadleDealsSaving)
                                {
                                    long id = await _tradesProcessor.Create(trade);
                                }

                                await natsClient.PubAsJsonAsync(_settings.Value.TradesQueueName, new Notification <Trade>()
                                {
                                    Code = ActionCode.CREATED.Code, Payload = trade
                                });
                            });

                            successKline.Data.ConnectionLost     += () => { _logger.LogError($"Connection to {Exchange} is lost"); };
                            successKline.Data.ConnectionRestored += (data) => { _logger.LogError($"Connection to {Exchange} is Restored"); };

                            while (!stoppingToken.IsCancellationRequested)
                            {
                            }

                            natsClient.Disconnect();
                            await client.Unsubscribe(successKline.Data);
                        }
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError($"{Exchange.Description} Trades service failed with message {ex.Message}", ex);
                }
            }
        }
Ejemplo n.º 7
0
        protected override void OnAfterEachTest()
        {
            _client1?.Disconnect();
            _client1?.Dispose();
            _client1 = null;

            _client2?.Disconnect();
            _client2?.Dispose();
            _client2 = null;

            _client3?.Disconnect();
            _client3?.Dispose();
            _client3 = null;
        }
Ejemplo n.º 8
0
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                try
                {
                    ConnectionInfo cnInfo = new ConnectionInfo(_settings.Value.BusConnectionString);
                    using (NatsClient natsClient = new NatsClient(cnInfo))
                    {
                        if (!natsClient.IsConnected)
                        {
                            natsClient.Connect();
                        }

                        await natsClient.SubAsync(_settings.Value.CandlesQueueName, stream => stream.Subscribe(msg =>
                        {
                            try
                            {
                                Task.Run(async() => await Process(msg, natsClient));
                            }
                            catch (Exception ex)
                            {
                                _logger.LogError($"TradingProcessor failed with message: {ex.Message}", ex);
                            }
                        }));

                        natsClient.Events.OfType <ClientDisconnected>().Subscribe(ev =>
                        {
                            Console.WriteLine($"Client was disconnected due to reason '{ev.Reason}'");

                            if (!cnInfo.AutoReconnectOnFailure)
                            {
                                ev.Client.Connect();
                            }
                        });

                        while (!stoppingToken.IsCancellationRequested)
                        {
                            await Task.Delay(TimeSpan.FromSeconds(1));
                        }

                        natsClient.Disconnect();
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex.Message);
                }
            }
        }
 /// <summary>
 /// Releases unmanaged and - optionally - managed resources.
 /// </summary>
 /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
 protected virtual void Dispose(bool disposing)
 {
     if (disposing && !_disposed)
     {
         if (_client != null && _client.IsConnected)
         {
             if (_subscription != null)
             {
                 _client.Unsub(_subscription);
                 _subscription = null;
             }
             _client.Disconnect();
         }
         _disposed = true;
     }
 }
Ejemplo n.º 10
0
        public void Dispose()
        {
            _sync?.Dispose();
            _sync = null;

            _client1?.Disconnect();
            _client1?.Dispose();
            _client1 = null;

            _client2?.Disconnect();
            _client2?.Dispose();
            _client2 = null;

            _client3?.Disconnect();
            _client3?.Dispose();
            _client3 = null;
        }
Ejemplo n.º 11
0
        public void IsMessageReceivedAfterLoggingIsDone()
        {
            var config = new NatsConfiguration
            {
                Host                   = "localhost",
                Port                   = 4222,
                ClientId               = "Serilog.Sinks.Nats.IntegrationTests.Publisher",
                Subject                = "IntegrationTest.TestSubject",
                RequestTimeoutMs       = 1000,
                AutoReconnectOnFailure = true,
                AutoRespondToPing      = true,
                BatchPostingLimit      = 1,
                Credentials            = new Credentials("test", "test"),
                Period                 = TimeSpan.FromMilliseconds(100),
                PubFlushMode           = PubFlushMode.Auto,
                SocketOptions          = new SocketOptions {
                    ConnectTimeoutMs = 1000, ReceiveBufferSize = 50000, ReceiveTimeoutMs = 5000, SendBufferSize = 50000, SendTimeoutMs = 5000
                },
                Verbose = false
            };

            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Debug()
                         .Enrich.FromLogContext()
                         .WriteTo.Nats(config, new JsonFormatter())
                         .CreateLogger();

            var cnInfo = new ConnectionInfo("localhost")
            {
                Credentials = new Credentials("test", "test"), RequestTimeoutMs = 30000
            };
            var client = new NatsClient("Serilog.Sinks.Nats.IntegrationTests.Subscriber", cnInfo);

            client.Connect();

            var foundMessage = false;

            client.SubWithHandlerAsync(config.Subject, msg => { foundMessage = true; }).ConfigureAwait(false);
            Log.Debug("Test message");

            Thread.Sleep(1000);
            client.Disconnect();

            Assert.True(foundMessage, "No log message received within timeout period");
        }
Ejemplo n.º 12
0
        protected override async Task DoWork(PairConfig pair, CancellationToken stoppingToken)
        {
            _logger.LogInformation($"{Exchange.Description} Candles worker is started");

            IPeriodCode candlePeriod = pair.Timeframe.HasValue ? PeriodCode.Create(pair.Timeframe.Value) : DefaultCandleInterval;

            while (!stoppingToken.IsCancellationRequested)
            {
                try
                {
                    using (BinanceSocketClient client = new BinanceSocketClient())
                    {
                        ConnectionInfo cnInfo = new ConnectionInfo(_settings.Value.BusConnectionString);
                        using (NatsClient natsClient = new NatsClient(cnInfo))
                        {
                            if (!natsClient.IsConnected)
                            {
                                natsClient.Connect();
                            }

                            CallResult <UpdateSubscription> successKline = client.SubscribeToKlineUpdates(pair.Symbol, candlePeriod.ToPeriodCode(), async(data) =>
                            {
                                await SaveCandle(data.Data, natsClient);
                            });

                            successKline.Data.ConnectionLost     += () => { _logger.LogError($"Connection to {Exchange} is lost"); };
                            successKline.Data.ConnectionRestored += (data) => { _logger.LogError($"Connection to {Exchange} is Restored"); };

                            while (!stoppingToken.IsCancellationRequested)
                            {
                            }

                            natsClient.Disconnect();
                            await client.Unsubscribe(successKline.Data);
                        }
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError($"{Exchange.Description} Candles service failed with message: {ex.Message}", ex);
                }
            }
        }
Ejemplo n.º 13
0
        public async Task Client_Should_not_reconnect_When_user_initiated_disconnect()
        {
            var wasDisconnectedDueToFailure = false;
            var wasDisconnected             = false;
            var wasReconnected = false;

            _sync = Sync.MaxTwo();

            var cnInfo = Context.GetConnectionInfo();

            cnInfo.AutoReconnectOnFailure = true;
            _client = new NatsClient(cnInfo);
            await _client.ConnectAsync();

            _client.Events
            .OfType <ClientDisconnected>()
            .Subscribe(ev =>
            {
                wasDisconnectedDueToFailure = ev.Reason == DisconnectReason.DueToFailure;
                wasDisconnected             = true;
                _sync.Release();
            });

            _client.Events
            .OfType <ClientConnected>()
            .Subscribe(ev =>
            {
                wasReconnected = true;
                _sync.Release();
            });

            _client.Disconnect();

            //Wait for the Disconnected release and the potential Connected release
            _sync.WaitForAny();

            wasDisconnectedDueToFailure.Should().BeFalse();
            wasDisconnected.Should().BeTrue();
            wasReconnected.Should().BeFalse();
            _client.IsConnected.Should().BeFalse();
        }
        public async Task Client_Should_not_reconnect_When_user_initiated_disconnect()
        {
            const string subject = "test";
            var          wasDisconnectedDueToFailure = false;
            var          wasDisconnected             = false;
            var          wasReconnected = false;

            _client = new NatsClient(_cnInfoWithAutoReconnect);
            _client.Connect();

            await _client.SubAsync(subject);

            _client.Events.OfType <ClientDisconnected>()
            .Subscribe(ev =>
            {
                wasDisconnectedDueToFailure = ev.Reason == DisconnectReason.DueToFailure;
                wasDisconnected             = true;
                ReleaseOne();
            });

            _client.Events.OfType <ClientConnected>()
            .Subscribe(ev =>
            {
                wasReconnected = true;
                ReleaseOne();
            });

            _client.Disconnect();

            //Wait for the Disconnected release and the potentiall Connected release
            WaitOne();
            WaitOne();

            wasDisconnectedDueToFailure.Should().BeFalse();
            wasDisconnected.Should().BeTrue();
            wasReconnected.Should().BeFalse();
            _client.IsConnected.Should().BeFalse();
        }
Ejemplo n.º 15
0
        public async Task Given_subscribed_When_disconnectiong_and_connecting_again_It_should_resubscribe_and_get_messages()
        {
            var subject        = GenerateSubject();
            var interceptCount = 0;

            _client.Sub(subject, stream => stream.Subscribe(NatsObserver.Delegating <MsgOp>(msg =>
            {
                Interlocked.Increment(ref interceptCount);
                ReleaseOne();
            })));

            await _client.PubAsync(subject, "Test1");

            WaitOne();
            _client.Disconnect();

            _client.Connect();
            await _client.PubAsync(subject, "Test2");

            WaitOne();

            interceptCount.Should().Be(2);
        }
Ejemplo n.º 16
0
        public async Task Given_subscribed_When_disconnectiong_and_connecting_again_It_should_resubscribe_and_get_messages()
        {
            var subject = Context.GenerateSubject();

            _sync   = Sync.MaxOne();
            _client = await Context.ConnectClientAsync();

            _client.Sub(subject, stream => stream.Subscribe(NatsObserver.Delegating <MsgOp>(msg => _sync.Release(msg))));

            await Context.DelayAsync();

            await _client.PubAsync(subject, "Test1");

            _sync.WaitForAny();
            _client.Disconnect();

            await _client.ConnectAsync();

            await _client.PubAsync(subject, "Test2");

            _sync.WaitForAny();

            _sync.InterceptedCount.Should().Be(2);
        }
        protected override async Task DoWork(PairConfig config, CancellationToken stoppingToken)
        {
            ExchangeConfig exchangeConfig = await _exchangeConfigProcessor.GetExchangeConfig(Exchange.Code);

            while (!stoppingToken.IsCancellationRequested)
            {
                try
                {
                    string listenKey = String.Empty;
                    using (BinanceClient client = new BinanceClient())
                    {
                        listenKey = client.StartUserStream().Data;
                    }

                    using (BinanceSocketClient socketClient = new BinanceSocketClient())
                    {
                        ConnectionInfo cnInfo = new ConnectionInfo(_settings.Value.BusConnectionString);
                        using (NatsClient natsClient = new NatsClient(cnInfo))
                        {
                            if (!natsClient.IsConnected)
                            {
                                natsClient.Connect();
                            }

                            CallResult <UpdateSubscription> successAccount = socketClient.SubscribeToUserDataUpdates(listenKey,
                                                                                                                     accountData =>
                            {
                            },
                                                                                                                     async orderData =>
                            {
                                Order order = orderData.ToOrder();
                                Deal deal   = await _dealProcessor.UpdateForOrder(order, config);

                                await natsClient.PubAsJsonAsync(_settings.Value.OrdersQueueName, new Notification <Deal>()
                                {
                                    Code = ActionCode.UPDATED.Code, Payload = deal
                                });
                            },
                                                                                                                     ocoOrderData =>
                            {
                            },
                                                                                                                     async balancesData =>
                            {
                                IEnumerable <Balance> balances = balancesData.Select(x => x.ToBalance());
                                foreach (Balance balance in balances)
                                {
                                    await _balanceProcessor.UpdateOrCreate(balance);
                                }
                            },
                                                                                                                     onAccountBalanceUpdate =>
                            {
                            });

                            while (!stoppingToken.IsCancellationRequested)
                            {
                            }

                            natsClient.Disconnect();
                            await socketClient.UnsubscribeAll();
                        }
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex.Message);
                }
            }
        }
 protected override void OnAfterEachTest()
 {
     _client?.Disconnect();
     _client?.Dispose();
     _client = null;
 }