Пример #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()));
        }
Пример #2
0
        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()));
        }
Пример #3
0
        /// <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);
                }
            }
        }
Пример #4
0
        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>();
        }
Пример #5
0
        public async Task Given_no_responder_exists_When_requesting_with_explicit_time_out_It_should_get_cancelled()
        {
            _requester = await Context.ConnectClientAsync();

            Func <Task> a = async() =>
            {
                var cts = new CancellationTokenSource(100);
                await _requester.RequestAsync("getValue", "foo value", cts.Token);
            };

            a.Should().Throw <TaskCanceledException>();
        }
Пример #6
0
        public async Task Given_multiple_responders_exists_and_non_inbox_requests_are_used_When_requesting_It_should_call_requester_once_and_dispatch_one_response()
        {
            _sync = Sync.MaxTwo();

            var cnInfoResponder = Context.GetConnectionInfo();
            var cnInfoRequester = cnInfoResponder.Clone();

            cnInfoRequester.UseInboxRequests = false;

            var value             = Guid.NewGuid().ToString("N");
            var responderReceived = new ConcurrentQueue <MsgOp>();
            var requesterReceived = new ConcurrentQueue <MsgOp>();
            var responsesReceived = new ConcurrentQueue <MsgOp>();

            _responder = await Context.ConnectClientAsync(cnInfoResponder);

            _requester = await Context.ConnectClientAsync(cnInfoRequester);

            _requester.MsgOpStream.Subscribe(msgOp => requesterReceived.Enqueue(msgOp));

            _responder.Sub("getValue", stream => stream.Subscribe(msg =>
            {
                responderReceived.Enqueue(msg);
                _responder.Pub(msg.ReplyTo, msg.GetPayloadAsString());
                _sync.Release();
            }));

            using (var responder2 = new NatsClient(cnInfoResponder))
            {
                await responder2.ConnectAsync();

                responder2.Sub("getValue", stream => stream.Subscribe(msg =>
                {
                    responderReceived.Enqueue(msg);
                    responder2.Pub(msg.ReplyTo, msg.GetPayloadAsString());
                    _sync.Release();
                }));

                await Context.DelayAsync();

                var response = await _requester.RequestAsync("getValue", value);

                responsesReceived.Enqueue(response);
            }

            _sync.WaitForAll();

            responsesReceived.Should().HaveCount(1);
            requesterReceived.Should().HaveCount(1);
            responderReceived.Should().HaveCount(2);
            responsesReceived.First().GetPayloadAsString().Should().Be(value);
        }
Пример #7
0
        public async Task Given_responder_exists_When_requesting_using_string_It_should_get_response()
        {
            var value = Guid.NewGuid().ToString("N");

            _responder.Sub("getValue", stream => stream.Subscribe(msg => _responder.Pub(msg.ReplyTo, msg.GetPayloadAsString())));

            var response = await _requester.RequestAsync("getValue", value);

            response.GetPayloadAsString().Should().Be(value);
        }
Пример #8
0
        public async Task Given_responder_exists_When_requesting_using_bytes_It_should_get_response()
        {
            var value = Guid.NewGuid().ToString("N");

            _responder = await Context.ConnectClientAsync();

            _requester = await Context.ConnectClientAsync();

            _responder.Sub("getValue", stream => stream.Subscribe(msg => _responder.Pub(msg.ReplyTo, msg.GetPayloadAsString())));

            await Context.DelayAsync();

            var response = await _requester.RequestAsync("getValue", Encoding.UTF8.GetBytes(value));

            response.GetPayloadAsString().Should().Be(value);
        }
Пример #9
0
        public async Task Given_responder_exists_When_requesting_using_string_It_should_get_response()
        {
            var value = Guid.NewGuid().ToString("N");

            var connectionInfo = Context
                                 .GetConnectionInfo()
                                 .AllowAllServerCertificates();

            _responder = await Context.ConnectClientAsync(connectionInfo);

            _requester = await Context.ConnectClientAsync(connectionInfo);

            _responder.Sub("getValue", stream => stream.Subscribe(msg => _responder.Pub(msg.ReplyTo, msg.GetPayloadAsString())));

            var response = await _requester.RequestAsync("getValue", value);

            response.GetPayloadAsString().Should().Be(value);
        }
Пример #10
0
        public static async Task RunAsync(ConnectionInfo cnInfo)
        {
            using (var client = new NatsClient("Requester", cnInfo))
            {
                client.Connect();

                while (true)
                {
                    Console.WriteLine("Request what? (blank=quit)");
                    var message = Console.ReadLine();
                    if (string.IsNullOrWhiteSpace(message))
                    {
                        break;
                    }

                    var response = await client.RequestAsync("demo-request", message);

                    Console.WriteLine($"Response: {response.GetPayloadAsString()}");
                }
            }
        }
Пример #11
0
        public static async Task <TimeSpan> MyNatsClientRequestAsync(int n, ReadOnlyMemory <byte> payload, bool useTls)
        {
            Console.WriteLine($"MyNatsClient-RequestAsync: n={n} s={payload.Length}");

            const string subject = "casea";

            using var cts  = new CancellationTokenSource();
            using var sync = new AutoResetEvent(false);
            var tcs    = new TaskCompletionSource <TimeSpan>();
            var cnInfo = new ConnectionInfo("127.0.0.1");

            if (useTls)
            {
                cnInfo.ServerCertificateValidation = (_, __, ___) => true;
            }

            var responderTask = Task.Factory.StartNew(async() =>
            {
                using var client = new NatsClient(cnInfo);
                await client.ConnectAsync().ConfigureAwait(false);

                client.Sub(subject, messages => messages.SubscribeSafe(msg => { client.Pub(msg.ReplyTo, msg.Payload); }));

                sync.Set();

                await tcs.Task.ConfigureAwait(false);
            }, cts.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default);

            var requesterTask = Task.Factory.StartNew(async() =>
            {
                using var client = new NatsClient(cnInfo);

                await client.ConnectAsync().ConfigureAwait(false);

                if (!sync.WaitOne(1000))
                {
                    throw new Exception("Responder does not seem to be started.");
                }

                for (var i = 0; i < 10; i++)
                {
                    await client.RequestAsync(subject, payload, cts.Token).ConfigureAwait(false);
                }

                var sw = Stopwatch.StartNew();

                for (var i = 0; i < n; i++)
                {
                    await client.RequestAsync(subject, payload, cts.Token).ConfigureAwait(false);
                }

                sw.Stop();
                tcs.SetResult(sw.Elapsed);
            }, cts.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default);

            var elapsed = await tcs.Task.ConfigureAwait(false);

            cts.Cancel();

            await Task.WhenAll(responderTask, requesterTask).ConfigureAwait(false);

            return(elapsed);
        }