You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@pulsar.apache.org by mm...@apache.org on 2019/03/14 20:20:00 UTC

[pulsar] branch master updated: Negative acks implementation for Python client (#3816)

This is an automated email from the ASF dual-hosted git repository.

mmerli pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/pulsar.git


The following commit(s) were added to refs/heads/master by this push:
     new d47ade8  Negative acks implementation for Python client (#3816)
d47ade8 is described below

commit d47ade850927c41d8612105cf8e900d17b116658
Author: Matteo Merli <mm...@apache.org>
AuthorDate: Thu Mar 14 13:19:54 2019 -0700

    Negative acks implementation for Python client (#3816)
    
    * Negative acks implementation for Python client
    
    * Fixed doc formatting
---
 pulsar-client-cpp/python/pulsar/__init__.py | 37 ++++++++++++++++++++++++++---
 pulsar-client-cpp/python/pulsar_test.py     | 30 +++++++++++++++++++++++
 pulsar-client-cpp/python/src/config.cc      |  2 ++
 pulsar-client-cpp/python/src/consumer.cc    | 10 ++++++++
 4 files changed, 76 insertions(+), 3 deletions(-)

diff --git a/pulsar-client-cpp/python/pulsar/__init__.py b/pulsar-client-cpp/python/pulsar/__init__.py
index 47a9808..8d972aa 100644
--- a/pulsar-client-cpp/python/pulsar/__init__.py
+++ b/pulsar-client-cpp/python/pulsar/__init__.py
@@ -68,8 +68,11 @@ To install the Python bindings:
 
     while True:
         msg = consumer.receive()
-        print("Received message '%s' id='%s'", msg.data().decode('utf-8'), msg.message_id())
-        consumer.acknowledge(msg)
+        try:
+            print("Received message '%s' id='%s'", msg.data().decode('utf-8'), msg.message_id())
+            consumer.acknowledge(msg)
+        except:
+            consumer.negative_acknowledge(msg)
 
     client.close()
 
@@ -470,6 +473,7 @@ class Client:
                   consumer_name=None,
                   unacked_messages_timeout_ms=None,
                   broker_consumer_stats_cache_time_ms=30000,
+                  negative_ack_redelivery_delay_ms=60000,
                   is_read_compacted=False,
                   properties=None,
                   pattern_auto_discovery_period=60
@@ -528,6 +532,9 @@ class Client:
           the given value is less than 10 seconds. If a successful
           acknowledgement is not sent within the timeout, all the unacknowledged
           messages are redelivered.
+        * `negative_ack_redelivery_delay_ms`:
+           The delay after which to redeliver the messages that failed to be
+           processed (with the `consumer.negative_acknowledge()`)
         * `broker_consumer_stats_cache_time_ms`:
           Sets the time duration for which the broker-side consumer stats will
           be cached in the client.
@@ -546,6 +553,8 @@ class Client:
         _check_type_or_none(str, consumer_name, 'consumer_name')
         _check_type_or_none(int, unacked_messages_timeout_ms, 'unacked_messages_timeout_ms')
         _check_type(int, broker_consumer_stats_cache_time_ms, 'broker_consumer_stats_cache_time_ms')
+        _check_type(int, negative_ack_redelivery_delay_ms, 'negative_ack_redelivery_delay_ms')
+        _check_type(int, pattern_auto_discovery_period, 'pattern_auto_discovery_period')
         _check_type(bool, is_read_compacted, 'is_read_compacted')
         _check_type_or_none(dict, properties, 'properties')
 
@@ -560,6 +569,8 @@ class Client:
             conf.consumer_name(consumer_name)
         if unacked_messages_timeout_ms:
             conf.unacked_messages_timeout_ms(unacked_messages_timeout_ms)
+
+        conf.negative_ack_redelivery_delay_ms(negative_ack_redelivery_delay_ms)
         conf.broker_consumer_stats_cache_time_ms(broker_consumer_stats_cache_time_ms)
         if properties:
             for k, v in properties.items():
@@ -815,7 +826,7 @@ class Producer:
         successfully persisted
         """
         self._producer.flush()
-        
+
 
     def close(self):
         """
@@ -941,6 +952,26 @@ class Consumer:
         else:
             self._consumer.acknowledge_cumulative(message)
 
+    def negative_acknowledge(self, message):
+        """
+        Acknowledge the failure to process a single message.
+
+        When a message is "negatively acked" it will be marked for redelivery after
+        some fixed delay. The delay is configurable when constructing the consumer
+        with {@link ConsumerConfiguration#setNegativeAckRedeliveryDelayMs}.
+
+        This call is not blocking.
+
+        **Args**
+
+        * `message`:
+          The received message or message id.
+        """
+        if isinstance(message, Message):
+            self._consumer.negative_acknowledge(message._message)
+        else:
+            self._consumer.negative_acknowledge(message)
+
     def pause_message_listener(self):
         """
         Pause receiving messages via the `message_listener` until
diff --git a/pulsar-client-cpp/python/pulsar_test.py b/pulsar-client-cpp/python/pulsar_test.py
index 8467dc3..18d1a23 100755
--- a/pulsar-client-cpp/python/pulsar_test.py
+++ b/pulsar-client-cpp/python/pulsar_test.py
@@ -916,6 +916,36 @@ class PulsarTest(TestCase):
         self.assertTrue(msg.topic_name() in partitions)
         client.close()
 
+    def test_negative_acks(self):
+        client = Client(self.serviceUrl)
+        consumer = client.subscribe('test_negative_acks',
+                                    'test',
+                                    schema=pulsar.schema.StringSchema())
+        producer = client.create_producer('test_negative_acks',
+                                          schema=pulsar.schema.StringSchema())
+        for i in range(10):
+            producer.send_async('hello-%d' % i, callback=None)
+
+        producer.flush()
+
+        for i in range(10):
+            msg = consumer.receive()
+            self.assertEqual(msg.value(), "hello-%d" % i)
+            consumer.negative_acknowledge(msg)
+
+        for i in range(10):
+            msg = consumer.receive()
+            self.assertEqual(msg.value(), "hello-%d" % i)
+            consumer.acknowledge(msg)
+
+        try:
+            # No more messages expected
+            msg = consumer.receive(100)
+            self.assertTrue(False)
+        except:
+            pass  # Exception is expected
+        client.close()
+
     def _check_value_error(self, fun):
         try:
             fun()
diff --git a/pulsar-client-cpp/python/src/config.cc b/pulsar-client-cpp/python/src/config.cc
index 5c54f45..2c985de 100644
--- a/pulsar-client-cpp/python/src/config.cc
+++ b/pulsar-client-cpp/python/src/config.cc
@@ -142,6 +142,8 @@ void export_config() {
             .def("consumer_name", &ConsumerConfiguration::setConsumerName)
             .def("unacked_messages_timeout_ms", &ConsumerConfiguration::getUnAckedMessagesTimeoutMs)
             .def("unacked_messages_timeout_ms", &ConsumerConfiguration::setUnAckedMessagesTimeoutMs)
+            .def("negative_ack_redelivery_delay_ms", &ConsumerConfiguration::getNegativeAckRedeliveryDelayMs)
+            .def("negative_ack_redelivery_delay_ms", &ConsumerConfiguration::setNegativeAckRedeliveryDelayMs)
             .def("broker_consumer_stats_cache_time_ms", &ConsumerConfiguration::getBrokerConsumerStatsCacheTimeInMs)
             .def("broker_consumer_stats_cache_time_ms", &ConsumerConfiguration::setBrokerConsumerStatsCacheTimeInMs)
             .def("pattern_auto_discovery_period", &ConsumerConfiguration::getPatternAutoDiscoveryPeriod)
diff --git a/pulsar-client-cpp/python/src/consumer.cc b/pulsar-client-cpp/python/src/consumer.cc
index 7c2a93a..99ea11a 100644
--- a/pulsar-client-cpp/python/src/consumer.cc
+++ b/pulsar-client-cpp/python/src/consumer.cc
@@ -74,6 +74,14 @@ void Consumer_acknowledge_message_id(Consumer& consumer, const MessageId& msgId)
     consumer.acknowledgeAsync(msgId, nullptr);
 }
 
+void Consumer_negative_acknowledge(Consumer& consumer, const Message& msg) {
+    consumer.negativeAcknowledge(msg);
+}
+
+void Consumer_negative_acknowledge_message_id(Consumer& consumer, const MessageId& msgId) {
+     consumer.negativeAcknowledge(msgId);
+}
+
 void Consumer_acknowledge_cumulative(Consumer& consumer, const Message& msg) {
     consumer.acknowledgeCumulativeAsync(msg, nullptr);
 }
@@ -122,6 +130,8 @@ void export_consumer() {
             .def("acknowledge", &Consumer_acknowledge_message_id)
             .def("acknowledge_cumulative", &Consumer_acknowledge_cumulative)
             .def("acknowledge_cumulative", &Consumer_acknowledge_cumulative_message_id)
+            .def("negative_acknowledge", &Consumer_negative_acknowledge)
+            .def("negative_acknowledge", &Consumer_negative_acknowledge_message_id)
             .def("close", &Consumer_close)
             .def("pause_message_listener", &Consumer_pauseMessageListener)
             .def("resume_message_listener", &Consumer_resumeMessageListener)