Exemple #1
0
        private async Task <MsgOp> DoRequestAsync(string subject, ReadOnlyMemory <byte> body, CancellationToken cancellationToken = default)
        {
            var replyToSubject = UniqueId.Generate();
            var taskComp       = new TaskCompletionSource <MsgOp>();

            using var _ = MsgOpStream
                          .WhereSubjectMatches(replyToSubject)
                          .SubscribeSafe(msg => taskComp.SetResult(msg), ex => taskComp.SetException(ex));

            using var cts = cancellationToken == default
                ? new CancellationTokenSource(_connectionInfo.RequestTimeoutMs)
                : CancellationTokenSource.CreateLinkedTokenSource(_cancellation.Token, cancellationToken);

            await using var __ = cts.Token.Register(() => taskComp.SetCanceled()).ConfigureAwait(false);

            cancellationToken.ThrowIfCancellationRequested();

            await _connection.WithWriteLockAsync(async (writer, arg) =>
            {
                var(subjectIn, bodyIn, replyToIn) = arg;
                var sid = UniqueId.Generate().AsMemory();

                await SubCmd.WriteAsync(writer, replyToIn, sid, ReadOnlyMemory <char> .Empty).ConfigureAwait(false);
                await UnsubCmd.WriteAsync(writer, sid, 1).ConfigureAwait(false);
                await writer.FlushAsync().ConfigureAwait(false);
                await PubCmd.WriteAsync(writer, subjectIn, replyToIn, bodyIn).ConfigureAwait(false);
                await writer.FlushAsync().ConfigureAwait(false);
            }, Tuple.Create(subject.AsMemory(), body, replyToSubject.AsMemory())).ConfigureAwait(false);

            return(await taskComp.Task.ConfigureAwait(false));
        }
Exemple #2
0
        public void Pub(string subject, ReadOnlyMemory <byte> body, string replyTo = null)
        {
            if (body.Length > _maxPayload)
            {
                throw NatsException.ExceededMaxPayload(_maxPayload, body.Length);
            }

            PubCmd.Write(_writer, subject, replyTo, body);
        }
Exemple #3
0
        public Task PubAsync(string subject, ReadOnlyMemory <byte> body, string replyTo = null)
        {
            if (body.Length > _maxPayload)
            {
                throw NatsException.ExceededMaxPayload(_maxPayload, body.Length);
            }

            return(PubCmd.WriteAsync(_writer, subject.AsMemory(), replyTo.AsMemory(), body));
        }
Exemple #4
0
        public void Pub(string subject, string body, string replyTo = null)
        {
            var payload = NatsEncoder.GetBytes(body);

            if (payload.Length > _maxPayload)
            {
                throw NatsException.ExceededMaxPayload(_maxPayload, payload.Length);
            }

            PubCmd.Write(_writer, subject, replyTo, payload);
        }
Exemple #5
0
        public Task PubAsync(string subject, string body, string replyTo = null)
        {
            var payload = NatsEncoder.GetBytes(body);

            if (payload.Length > _maxPayload)
            {
                throw NatsException.ExceededMaxPayload(_maxPayload, payload.Length);
            }

            return(PubCmd.WriteAsync(_writer, subject.AsMemory(), replyTo.AsMemory(), payload));
        }
Exemple #6
0
        private async Task <MsgOp> DoRequestAsync(string subject, byte[] body, int?timeoutMs)
        {
            var requestReplyAddress = $"{Guid.NewGuid():N}";
            var pubCmd = PubCmd.Generate(subject, body, requestReplyAddress);

            var taskComp            = new TaskCompletionSource <MsgOp>();
            var requestSubscription = MsgOpStream.Where(msg => msg.Subject == requestReplyAddress).Subscribe(
                msg => taskComp.SetResult(msg),
                ex => taskComp.SetException(ex));

            var subscriptionInfo = new SubscriptionInfo(requestReplyAddress, maxMessages: 1);
            var subCmd           = SubCmd.Generate(subscriptionInfo.Subject, subscriptionInfo.Id);
            var unsubCmd         = UnsubCmd.Generate(subscriptionInfo.Id, subscriptionInfo.MaxMessages);

            await _connection.WithWriteLockAsync(async writer =>
            {
                await writer.WriteAsync(subCmd).ConfigureAwait(false);
                await writer.WriteAsync(unsubCmd).ConfigureAwait(false);
                await writer.FlushAsync().ConfigureAwait(false);
                await writer.WriteAsync(pubCmd).ConfigureAwait(false);
                await writer.FlushAsync().ConfigureAwait(false);
            }).ConfigureAwait(false);

            Task.WaitAny(new[] { Task.Delay(timeoutMs ?? _connectionInfo.RequestTimeoutMs), taskComp.Task }, _cancellation.Token);
            if (!taskComp.Task.IsCompleted)
            {
                taskComp.SetException(NatsException.RequestTimedOut());
            }

            return(await taskComp.Task
                   .ContinueWith(t =>
            {
                requestSubscription?.Dispose();

                if (!t.IsFaulted)
                {
                    return t.Result;
                }

                var ex = t.Exception?.GetBaseException() ?? t.Exception;
                if (ex == null)
                {
                    return t.Result;
                }

                _logger.Error("Exception while performing request.", ex);

                throw ex;
            })
                   .ConfigureAwait(false));
        }
Exemple #7
0
        public async Task PubAsync(string subject, string body, string replyTo = null)
        {
            ThrowIfDisposed();

            var cmdPayload = PubCmd.Generate(subject, body, replyTo);

            await _connection.WithWriteLockAsync(async writer =>
            {
                await writer.WriteAsync(cmdPayload).ConfigureAwait(false);
                if (ShouldAutoFlush)
                {
                    await writer.FlushAsync().ConfigureAwait(false);
                }
            }).ConfigureAwait(false);
        }
Exemple #8
0
        public void Pub(string subject, IPayload body, string replyTo = null)
        {
            ThrowIfDisposed();

            var cmdPayload = PubCmd.Generate(subject, body, replyTo);

            _connection.WithWriteLock(writer =>
            {
                writer.Write(cmdPayload);
                if (ShouldAutoFlush)
                {
                    writer.Flush();
                }
            });
        }
Exemple #9
0
        private async Task <MsgOp> DoRequestUsingInboxAsync(string subject, ReadOnlyMemory <byte> body, CancellationToken cancellationToken = default)
        {
            var requestId      = UniqueId.Generate();
            var replyToSubject = $"{_inboxAddress}.{requestId}";
            var taskComp       = new TaskCompletionSource <MsgOp>();

            if (!_outstandingRequests.TryAdd(requestId, taskComp))
            {
                throw NatsException.InitRequestError("Unable to initiate request.");
            }

            using var cts = cancellationToken == default
                ? new CancellationTokenSource(_connectionInfo.RequestTimeoutMs)
                : CancellationTokenSource.CreateLinkedTokenSource(_cancellation.Token, cancellationToken);

            await using var _ = cts.Token.Register(() =>
            {
                if (_outstandingRequests.TryRemove(requestId, out var ts))
                {
                    ts.TrySetCanceled();
                }
            }).ConfigureAwait(false);

            cancellationToken.ThrowIfCancellationRequested();

            await _connection.WithWriteLockAsync(async (writer, arg) =>
            {
                var(subjectIn, bodyIn, replyToIn) = arg;

                if (_inboxSubscription == null)
                {
                    SetupInboxSubscription();

                    await SubCmd.WriteAsync(
                        writer,
                        _inboxSubscription.SubscriptionInfo.Subject.AsMemory(),
                        _inboxSubscription.SubscriptionInfo.Id.AsMemory(),
                        _inboxSubscription.SubscriptionInfo.QueueGroup.AsMemory()).ConfigureAwait(false);
                }

                await PubCmd.WriteAsync(writer, subjectIn, replyToIn, bodyIn).ConfigureAwait(false);
                await writer.FlushAsync().ConfigureAwait(false);
            }, Tuple.Create(subject.AsMemory(), body, replyToSubject.AsMemory())).ConfigureAwait(false);

            return(await taskComp.Task.ConfigureAwait(false));
        }
Exemple #10
0
        public async Task PubAsync(string subject, ReadOnlyMemory <byte> body, string replyTo = null)
        {
            ThrowIfDisposed();

            if (body.Length > _connection.ServerInfo.MaxPayload)
            {
                throw NatsException.ExceededMaxPayload(_connection.ServerInfo.MaxPayload, body.Length);
            }

            await _connection.WithWriteLockAsync(async (writer, arg) =>
            {
                var(subjectIn, bodyIn, replyToIn) = arg;
                await PubCmd.WriteAsync(writer, subjectIn, replyToIn, bodyIn).ConfigureAwait(false);
                if (ShouldAutoFlush)
                {
                    await writer.FlushAsync().ConfigureAwait(false);
                }
            }, Tuple.Create(subject.AsMemory(), body, replyTo.AsMemory())).ConfigureAwait(false);
        }
Exemple #11
0
        public void Pub(string subject, ReadOnlyMemory <byte> body, string replyTo = null)
        {
            ThrowIfDisposed();

            if (body.Length > _connection.ServerInfo.MaxPayload)
            {
                throw NatsException.ExceededMaxPayload(_connection.ServerInfo.MaxPayload, body.Length);
            }

            _connection.WithWriteLock((writer, arg) =>
            {
                var(subjectIn, bodyIn, replyToIn) = arg;

                PubCmd.Write(writer, subjectIn.Span, replyToIn.Span, bodyIn);
                if (ShouldAutoFlush)
                {
                    writer.Flush();
                }
            }, Tuple.Create(subject.AsMemory(), body, replyTo.AsMemory()));
        }
Exemple #12
0
 public async Task PubAsync(string subject, IPayload body, string replyTo = null)
 => await _pubPayloadAsync(PubCmd.Generate(subject, body, replyTo)).ConfigureAwait(false);
Exemple #13
0
 public async Task PubAsync(string subject, byte[] body, string replyTo = null)
 => await _pubBytesAsync(PubCmd.Generate(subject, body, replyTo)).ConfigureAwait(false);
Exemple #14
0
 public void Pub(string subject, IPayload body, string replyTo = null)
 => _pubPayloadSync(PubCmd.Generate(subject, body, replyTo));
Exemple #15
0
 public void Pub(string subject, byte[] body, string replyTo = null)
 => _pubBytesSync(PubCmd.Generate(subject, body, replyTo));