ivankelly commented on a change in pull request #1996: Cpp client: add multiTopicsConsumer URL: https://github.com/apache/incubator-pulsar/pull/1996#discussion_r197729701
########## File path: pulsar-client-cpp/lib/MultiTopicsConsumerImpl.cc ########## @@ -0,0 +1,621 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +#include "MultiTopicsConsumerImpl.h" + +DECLARE_LOG_OBJECT() + +using namespace pulsar; + +MultiTopicsConsumerImpl::MultiTopicsConsumerImpl(ClientImplPtr client, const std::vector<std::string>& topics, + const std::string& subscriptionName, TopicNamePtr topicName, + const ConsumerConfiguration& conf, + const LookupServicePtr lookupServicePtr) + : client_(client), + subscriptionName_(subscriptionName), + topic_(topicName ? topicName->toString() : "EmptyTopics"), + conf_(conf), + state_(Pending), + messages_(1000), + listenerExecutor_(client->getListenerExecutorProvider()->get()), + messageListener_(conf.getMessageListener()), + namespaceName_(topicName ? topicName->getNamespaceName() : boost::shared_ptr<NamespaceName>()), + lookupServicePtr_(lookupServicePtr), + allTopicPartitionsNumber_(boost::make_shared<std::atomic<int>>(0)), + topics_(topics) { + std::stringstream consumerStrStream; + consumerStrStream << "[Muti Topics Consumer: " + << "TopicName - " << topic_ << " - Subscription - " << subscriptionName << "]"; + consumerStr_ = consumerStrStream.str(); + + if (conf.getUnAckedMessagesTimeoutMs() != 0) { + unAckedMessageTrackerPtr_.reset( + new UnAckedMessageTrackerEnabled(conf.getUnAckedMessagesTimeoutMs(), client, *this)); + } else { + unAckedMessageTrackerPtr_.reset(new UnAckedMessageTrackerDisabled()); + } +} + +void MultiTopicsConsumerImpl::start() { + if (topics_.empty()) { + setState(Ready); + LOG_DEBUG("No topics passed in when create MultiTopicsConsumer."); + multiTopicsConsumerCreatedPromise_.setValue(shared_from_this()); + return; + } + + // start call subscribeOneTopicAsync for each single topic + int topicsNumber = topics_.size(); + boost::shared_ptr<std::atomic<int>> topicsNeedCreate = boost::make_shared<std::atomic<int>>(topicsNumber); + // subscribe for each passed in topic + for (std::vector<std::string>::const_iterator itr = topics_.begin(); itr != topics_.end(); itr++) { + subscribeOneTopicAsync(*itr).addListener( + boost::bind(&MultiTopicsConsumerImpl::handleOneTopicSubscribed, shared_from_this(), _1, _2, *itr, + topicsNeedCreate)); + } +} + +void MultiTopicsConsumerImpl::handleOneTopicSubscribed(Result result, Consumer consumer, + const std::string& topic, + boost::shared_ptr<std::atomic<int>> topicsNeedCreate) { + int previous = topicsNeedCreate->fetch_sub(1); + assert(previous > 0); + + if (result != ResultOk) { + state_ = Failed; + multiTopicsConsumerCreatedPromise_.setFailed(result); + // unsubscribed all of the successfully subscribed partitioned consumers + ResultCallback nullCallbackForCleanup = NULL; + closeAsync(nullCallbackForCleanup); + LOG_ERROR("Unable to create Consumer - " + << " Error - " << result); + return; + } + + LOG_DEBUG("Successfully Subscribed to topic " << topic << " in TopicsConsumer "); + + if (topicsNeedCreate->load() == 0) { + LOG_INFO("Successfully Subscribed to Topics"); + setState(Ready); + if (!namespaceName_) { + namespaceName_ = TopicName::get(topic)->getNamespaceName(); + } + multiTopicsConsumerCreatedPromise_.setValue(shared_from_this()); + return; + } +} + +// subscribe for passed in topic +Future<Result, Consumer> MultiTopicsConsumerImpl::subscribeOneTopicAsync(const std::string& topic) { + TopicNamePtr topicName; + ConsumerSubResultPromisePtr topicPromise = boost::make_shared<Promise<Result, Consumer>>(); + if (!(topicName = TopicName::get(topic))) { + LOG_ERROR("TopicName invalid: " << topic); + topicPromise->setFailed(ResultInvalidTopicName); + return topicPromise->getFuture(); + } + + if (state_ == Closed || state_ == Closing) { + LOG_ERROR("MultiTopicsConsumer already closed when subscribe."); + topicPromise->setFailed(ResultAlreadyClosed); + return topicPromise->getFuture(); + } + + // subscribe for each partition, when all partitions completed, complete promise + lookupServicePtr_->getPartitionMetadataAsync(topicName).addListener( + boost::bind(&MultiTopicsConsumerImpl::subscribeTopicPartitions, shared_from_this(), _1, _2, topicName, + subscriptionName_, conf_, topicPromise)); + return topicPromise->getFuture(); +} + +void MultiTopicsConsumerImpl::subscribeTopicPartitions(const Result result, + const LookupDataResultPtr partitionMetadata, + TopicNamePtr topicName, + const std::string& consumerName, + ConsumerConfiguration conf, + ConsumerSubResultPromisePtr topicSubResultPromise) { + if (result != ResultOk) { + LOG_ERROR("Error Checking/Getting Partition Metadata while MultiTopics Subscribing- " << result) + topicSubResultPromise->setFailed(result); + return; + } + + boost::shared_ptr<ConsumerImpl> consumer; + ConsumerConfiguration config; + ExecutorServicePtr internalListenerExecutor = client_->getPartitionListenerExecutorProvider()->get(); + + // all the consumers should have same name. + config.setConsumerName(conf_.getConsumerName()); + config.setConsumerType(conf_.getConsumerType()); + config.setBrokerConsumerStatsCacheTimeInMs(conf_.getBrokerConsumerStatsCacheTimeInMs()); + config.setMessageListener( + boost::bind(&MultiTopicsConsumerImpl::messageReceived, shared_from_this(), _1, _2)); + config.setReceiverQueueSize(conf_.getReceiverQueueSize()); + + int partitionsNumber = partitionMetadata->getPartitions() >= 1 ? partitionMetadata->getPartitions() : 1; + + Lock lock(mutex_); + topicsPartitions_.insert(std::make_pair(topicName->toString(), partitionsNumber)); + lock.unlock(); + allTopicPartitionsNumber_->fetch_add(partitionsNumber); + + boost::shared_ptr<std::atomic<int>> partitionsNeedCreate = + boost::make_shared<std::atomic<int>>(partitionsNumber); + + for (int i = 0; i < partitionsNumber; i++) { + std::string topicPartitionName = topicName->getTopicPartitionName(i); + consumer = boost::make_shared<ConsumerImpl>(client_, topicPartitionName, subscriptionName_, config, + internalListenerExecutor, Partitioned); + consumer->getConsumerCreatedFuture().addListener( + boost::bind(&MultiTopicsConsumerImpl::handleSingleConsumerCreated, shared_from_this(), _1, _2, + partitionsNeedCreate, topicSubResultPromise)); + consumer->setPartitionIndex(i); + consumers_.insert(std::make_pair(topicPartitionName, consumer)); + LOG_DEBUG("Create Consumer for - " << topicPartitionName << " - " << consumerStr_); + consumer->start(); + } +} + +void MultiTopicsConsumerImpl::handleSingleConsumerCreated( + Result result, ConsumerImplBaseWeakPtr consumerImplBaseWeakPtr, + boost::shared_ptr<std::atomic<int>> partitionsNeedCreate, + ConsumerSubResultPromisePtr topicSubResultPromise) { + if (state_ == Failed) { + // one of the consumer creation failed, and we are cleaning up + topicSubResultPromise->setFailed(ResultAlreadyClosed); + LOG_ERROR("Unable to create Consumer - state == Failed, result: " << result); + return; + } + + int previous = partitionsNeedCreate->fetch_sub(1); + assert(previous > 0); + + if (result != ResultOk) { + state_ = Failed; + topicSubResultPromise->setFailed(result); + LOG_ERROR("Unable to create Consumer - " + << " Error - " << result); + return; + } + + LOG_DEBUG("Successfully Subscribed to a single partition of topic in TopicsConsumer. " + << "Partitions need to create - " << previous - 1); + + if (partitionsNeedCreate->load() == 0) { + topicSubResultPromise->setValue(Consumer(shared_from_this())); + return; + } +} + +void MultiTopicsConsumerImpl::unsubscribeAsync(ResultCallback callback) { + LOG_INFO("[ Topics Consumer " << topic_ << "," << subscriptionName_ << "] Unsubscribing"); + + Lock lock(mutex_); + if (state_ == Closing || state_ == Closed) { + LOG_INFO(consumerStr_ << " already closed"); + lock.unlock(); + callback(ResultAlreadyClosed); + return; + } + state_ = Closing; + lock.unlock(); + + boost::shared_ptr<std::atomic<int>> consumerUnsubed = boost::make_shared<std::atomic<int>>(0); + + for (ConsumerMap::const_iterator consumer = consumers_.begin(); consumer != consumers_.end(); + consumer++) { + LOG_DEBUG("Unsubcribing Consumer - " << consumer->first); + (consumer->second) + ->unsubscribeAsync(boost::bind(&MultiTopicsConsumerImpl::handleUnsubscribedAsync, + shared_from_this(), _1, consumerUnsubed, callback)); + } +} + +void MultiTopicsConsumerImpl::handleUnsubscribedAsync(Result result, + boost::shared_ptr<std::atomic<int>> consumerUnsubed, + ResultCallback callback) { + int previous = consumerUnsubed->fetch_add(1); + assert(previous < allTopicPartitionsNumber_->load()); + + if (result != ResultOk) { + setState(Failed); + LOG_ERROR("Error Closing one of the consumers in TopicsConsumer, result: " + << result << " subscription - " << subscriptionName_); + } + + if (consumerUnsubed->load() == allTopicPartitionsNumber_->load()) { Review comment: rename allTopicPartitionsNumber_ to numTopicPartitions_ ---------------------------------------------------------------- This is an automated message from the Apache Git Service. To respond to the message, please log on GitHub and use the URL above to go to the specific comment. For queries about this service, please contact Infrastructure at: us...@infra.apache.org With regards, Apache Git Services