Exemplo n.º 1
0
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            NeoService.Notify += NeoService_Notify;
            var neo = new MainService().StartUpNode();

            _decision = new Decision(neo);
            await using var client = PulsarClient.Builder().Build();
            _producer = client.NewProducer()
                        .Topic("persistent://public/default/smartcontract")
                        .Create();
            _consumer = client.NewConsumer()
                        .SubscriptionName("persistent://public/default/decision")
                        .Topic("Decision")
                        .Create();
            while (!stoppingToken.IsCancellationRequested)
            {
                _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
                await foreach (var message in _consumer.Messages())
                {
                    Console.WriteLine("Received: " + Encoding.UTF8.GetString(message.Data.ToArray()));

                    await _consumer.Acknowledge(message);
                }
                await Task.Delay(1000, stoppingToken);
            }
        }
Exemplo n.º 2
0
        private static async Task OnMessageReceived(object sender, MessageReceivedEventArgs args)
        {
            var testMessage = (TestMessage)args.Message.Endpoint.Serializer.Deserialize(
                args.Message.RawContent,
                new MessageHeaderCollection(args.Message.Headers));

            Console.WriteLine($"[{testMessage.Id}] [{Activity.Current.Id}] {testMessage.Text}");

            var text = testMessage.Text.ToLower().Trim();

            if (text == "bad")
            {
                Console.WriteLine("--> Bad message, throwing exception!");
                throw new Exception("Bad!");
            }

            if (text.StartsWith("delay"))
            {
                if (int.TryParse(text.Substring(5), out int delay) && delay > 0)
                {
                    Console.WriteLine($"--> Delaying execution of {delay} seconds!");
                    Thread.Sleep(delay * 1000);
                }
            }

            await _consumer.Acknowledge(args.Message.Offset);
        }
Exemplo n.º 3
0
        private async Task ConsumeAsync(IListeningWorkerQueue callback)
        {
            await foreach (Message message in _consumer.Messages(_cancellation))
            {
                Envelope envelope;

                try
                {
                    envelope = _protocol.ReadEnvelope(new DotPulsarMessage(message.Data, message.Properties));
                }
                catch (Exception ex)
                {
                    _logger.LogException(ex, message: $"Error trying to map an incoming Pulsar {_endpoint.Topic} Topic message to an Envelope. See the Dead Letter Queue");
                    continue;
                }

                try
                {
                    await callback.Received(Address, envelope);

                    await _consumer.Acknowledge(message, _cancellation);
                }
                catch (Exception e)
                {
                    // DotPulsar currently doesn't support Nack so will likely just keep retrying message for now.
                    _logger.LogException(e, envelope.Id, "Error trying to receive a message from " + Address);
                }
            }
        }
Exemplo n.º 4
0
        private static void OnMessageReceived(object sender, MessageReceivedEventArgs args)
        {
            var testMessage = args.Endpoint.Serializer.Deserialize(args.Message) as TestMessage;

            if (testMessage == null)
            {
                Console.WriteLine("Received a weird message!");
                return;
            }

            Console.WriteLine($"[{testMessage.Id}] {testMessage.Text}");

            var text = testMessage.Text.ToLower().Trim();

            if (text == "bad")
            {
                Console.WriteLine("--> Bad message, throwing exception!");
                throw new Exception("Bad!");
            }
            else if (text.StartsWith("delay"))
            {
                if (int.TryParse(text.Substring(5), out int delay) && delay > 0)
                {
                    Console.WriteLine($"--> Delaying execution of {delay} seconds!");
                    Thread.Sleep(delay * 1000);
                }
            }

            _consumer.Acknowledge(args.Offset);
        }
Exemplo n.º 5
0
 private static async Task ConsumeMessages(IConsumer <string> consumer, CancellationToken cancellationToken)
 {
     try
     {
         await foreach (var message in consumer.Messages(cancellationToken))
         {
             Console.WriteLine("Received: " + message.Value());
             await consumer.Acknowledge(message, cancellationToken);
         }
     }
     catch (OperationCanceledException) { }
 }
Exemplo n.º 6
0
 private static async Task ConsumeMessages(IConsumer consumer, CancellationToken cancellationToken)
 {
     try
     {
         await foreach (var message in consumer.Messages(cancellationToken))
         {
             var data = Encoding.UTF8.GetString(message.Data.ToArray());
             Console.WriteLine("Received: " + data);
             await consumer.Acknowledge(message, cancellationToken);
         }
     }
     catch (OperationCanceledException) { }
 }
Exemplo n.º 7
0
        /// <summary>
        /// Process and auto-acknowledge a message.
        /// </summary>
        public static async ValueTask Process <TMessage>(
            this IConsumer <TMessage> consumer,
            Func <IMessage <TMessage>, CancellationToken, ValueTask> processor,
            CancellationToken cancellationToken = default)
        {
            const string operation     = "process";
            var          operationName = $"{consumer.Topic} {operation}";

            var tags = new KeyValuePair <string, object?>[]
            {
                new KeyValuePair <string, object?>("messaging.destination", consumer.Topic),
                new KeyValuePair <string, object?>("messaging.destination_kind", "topic"),
                new KeyValuePair <string, object?>("messaging.operation", operation),
                new KeyValuePair <string, object?>("messaging.system", "pulsar"),
                new KeyValuePair <string, object?>("messaging.url", consumer.ServiceUrl),
                new KeyValuePair <string, object?>("messaging.pulsar.subscription", consumer.SubscriptionName)
            };

            while (!cancellationToken.IsCancellationRequested)
            {
                var message = await consumer.Receive(cancellationToken).ConfigureAwait(false);

                var activity = DotPulsarActivitySource.StartConsumerActivity(message, operationName, tags);

                if (activity is not null && activity.IsAllDataRequested)
                {
                    activity.SetMessageId(message.MessageId);
                    activity.SetPayloadSize(message.Data.Length);
                    activity.SetStatusCode("OK");
                }

                try
                {
                    await processor(message, cancellationToken).ConfigureAwait(false);
                }
                catch (Exception exception)
                {
                    if (activity is not null && activity.IsAllDataRequested)
                    {
                        activity.AddException(exception);
                    }
                }

                activity?.Dispose();

                await consumer.Acknowledge(message.MessageId, cancellationToken).ConfigureAwait(false);
            }
        }
Exemplo n.º 8
0
 /// <summary>
 /// Acknowledge the consumption of a single message.
 /// </summary>
 public static async ValueTask Acknowledge(this IConsumer consumer, IMessage message, CancellationToken cancellationToken = default)
 => await consumer.Acknowledge(message.MessageId, cancellationToken).ConfigureAwait(false);
Exemplo n.º 9
0
 private void Commit(IEnumerable <IOffset> offsets, IServiceProvider serviceProvider)
 {
     _commitHandler?.Invoke(serviceProvider);
     _consumer.Acknowledge(offsets);
 }
Exemplo n.º 10
0
 public Task Complete(Envelope envelope) => _consumer.Acknowledge(_messageId).AsTask();